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/DependencyResolver/Operation/InstallOperation.php
src/Composer/DependencyResolver/Operation/InstallOperation.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\DependencyResolver\Operation; use Composer\Package\PackageInterface; /** * Solver install operation. * * @author Konstantin Kudryashov <ever.zet@gmail.com> */ class InstallOperation extends SolverOperation implements OperationInterface { protected const TYPE = 'install'; /** * @var PackageInterface */ protected $package; public function __construct(PackageInterface $package) { $this->package = $package; } /** * Returns package instance. */ public function getPackage(): PackageInterface { return $this->package; } /** * @inheritDoc */ public function show($lock): string { return self::format($this->package, $lock); } public static function format(PackageInterface $package, bool $lock = false): string { return ($lock ? 'Locking ' : 'Installing ').'<info>'.$package->getPrettyName().'</info> (<comment>'.$package->getFullPrettyVersion().'</comment>)'; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Advisory/PartialSecurityAdvisory.php
src/Composer/Advisory/PartialSecurityAdvisory.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\Advisory; use Composer\Pcre\Preg; use Composer\Semver\Constraint\Constraint; use Composer\Semver\Constraint\ConstraintInterface; use Composer\Semver\VersionParser; use JsonSerializable; class PartialSecurityAdvisory implements JsonSerializable { /** * @var string * @readonly */ public $advisoryId; /** * @var string * @readonly */ public $packageName; /** * @var ConstraintInterface * @readonly */ public $affectedVersions; /** * @param array<mixed> $data * @return SecurityAdvisory|PartialSecurityAdvisory */ public static function create(string $packageName, array $data, VersionParser $parser): self { try { $constraint = $parser->parseConstraints($data['affectedVersions']); } catch (\UnexpectedValueException $e) { // try to keep only the essential part of the constraint to turn invalid ones like <=3.20-test2 into <=3.20 which is better than nothing try { $affectedVersion = Preg::replace('{(^[>=<^~]*[\d.]+).*}', '$1', $data['affectedVersions']); $constraint = $parser->parseConstraints($affectedVersion); } catch (\UnexpectedValueException $e) { $constraint = new Constraint('==', '0.0.0-invalid-version'); } } if (isset($data['title'], $data['sources'], $data['reportedAt'])) { return new SecurityAdvisory($packageName, $data['advisoryId'], $constraint, $data['title'], $data['sources'], new \DateTimeImmutable($data['reportedAt'], new \DateTimeZone('UTC')), $data['cve'] ?? null, $data['link'] ?? null, $data['severity'] ?? null); } return new self($packageName, $data['advisoryId'], $constraint); } public function __construct(string $packageName, string $advisoryId, ConstraintInterface $affectedVersions) { $this->advisoryId = $advisoryId; $this->packageName = $packageName; $this->affectedVersions = $affectedVersions; } /** * @return mixed */ #[\ReturnTypeWillChange] public function jsonSerialize() { $data = (array) $this; $data['affectedVersions'] = $data['affectedVersions']->getPrettyString(); return $data; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Advisory/IgnoredSecurityAdvisory.php
src/Composer/Advisory/IgnoredSecurityAdvisory.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\Advisory; use Composer\Semver\Constraint\ConstraintInterface; use DateTimeImmutable; class IgnoredSecurityAdvisory extends SecurityAdvisory { /** * @var string|null * @readonly */ public $ignoreReason; /** * @param non-empty-array<array{name: string, remoteId: string}> $sources */ public function __construct(string $packageName, string $advisoryId, ConstraintInterface $affectedVersions, string $title, array $sources, DateTimeImmutable $reportedAt, ?string $cve = null, ?string $link = null, ?string $ignoreReason = null, ?string $severity = null) { parent::__construct($packageName, $advisoryId, $affectedVersions, $title, $sources, $reportedAt, $cve, $link, $severity); $this->ignoreReason = $ignoreReason; } /** * @return mixed */ #[\ReturnTypeWillChange] public function jsonSerialize() { $data = parent::jsonSerialize(); if ($this->ignoreReason === null) { unset($data['ignoreReason']); } return $data; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Advisory/AuditConfig.php
src/Composer/Advisory/AuditConfig.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\Advisory; use Composer\Config; /** * @readonly * @internal */ class AuditConfig { /** * @var bool Whether to run audit */ public $audit; /** * @var Auditor::FORMAT_* */ public $auditFormat; /** * @var Auditor::ABANDONED_* */ public $auditAbandoned; /** * @var bool Should insecure versions be blocked during a composer update/required command */ public $blockInsecure; /** * @var bool Should abandoned packages be blocked during a composer update/required command */ public $blockAbandoned; /** * @var bool Should repositories that are unreachable or return a non-200 status code be ignored. */ public $ignoreUnreachable; /** * @var array<string, string|null> List of advisory IDs to ignore during auditing => reason for ignoring */ public $ignoreListForAudit; /** * @var array<string, string|null> List of advisory IDs to ignore during blocking */ public $ignoreListForBlocking; /** * @var array<string, string|null> List of severities to ignore during auditing */ public $ignoreSeverityForAudit; /** * @var array<string, string|null> List of severities to ignore during blocking */ public $ignoreSeverityForBlocking; /** * @var array<string, string|null> List of abandoned packages to ignore during auditing */ public $ignoreAbandonedForAudit; /** * @var array<string, string|null> List of abandoned packages to ignore during blocking */ public $ignoreAbandonedForBlocking; /** * @param Auditor::FORMAT_* $auditFormat * @param Auditor::ABANDONED_* $auditAbandoned * @param array<string, string|null> $ignoreListForAudit * @param array<string, string|null> $ignoreListForBlocking * @param array<string, string|null> $ignoreSeverityForAudit * @param array<string, string|null> $ignoreSeverityForBlocking * @param array<string, string|null> $ignoreAbandonedForAudit * @param array<string, string|null> $ignoreAbandonedForBlocking */ public function __construct(bool $audit, string $auditFormat, string $auditAbandoned, bool $blockInsecure, bool $blockAbandoned, bool $ignoreUnreachable, array $ignoreListForAudit, array $ignoreListForBlocking, array $ignoreSeverityForAudit, array $ignoreSeverityForBlocking, array $ignoreAbandonedForAudit, array $ignoreAbandonedForBlocking) { $this->audit = $audit; $this->auditFormat = $auditFormat; $this->auditAbandoned = $auditAbandoned; $this->blockInsecure = $blockInsecure; $this->blockAbandoned = $blockAbandoned; $this->ignoreUnreachable = $ignoreUnreachable; $this->ignoreListForAudit = $ignoreListForAudit; $this->ignoreListForBlocking = $ignoreListForBlocking; $this->ignoreSeverityForAudit = $ignoreSeverityForAudit; $this->ignoreSeverityForBlocking = $ignoreSeverityForBlocking; $this->ignoreAbandonedForAudit = $ignoreAbandonedForAudit; $this->ignoreAbandonedForBlocking = $ignoreAbandonedForBlocking; } /** * Parse ignore configuration supporting both simple and detailed formats with apply scopes * * Simple format: ['CVE-123', 'CVE-456'] or ['CVE-123' => 'reason'] * Detailed format: ['CVE-123' => ['apply' => 'audit|block|all', 'reason' => '...']] * * @param array<mixed> $config * @return array{audit: array<string, string|null>, block: array<string, string|null>} */ private static function parseIgnoreWithApply(array $config): array { $forAudit = []; $forBlock = []; foreach ($config as $key => $value) { // Simple format: ['CVE-123'] if (is_int($key) && is_string($value)) { $id = $value; $apply = 'all'; $reason = null; } // Simple format with reason: ['CVE-123' => 'reason'] elseif (is_string($value)) { $id = $key; $apply = 'all'; $reason = $value; } // Detailed format: ['CVE-123' => ['apply' => '...', 'reason' => '...']] elseif (is_array($value)) { $id = $key; $apply = $value['apply'] ?? 'all'; $reason = $value['reason'] ?? null; // Validate apply value if (!in_array($apply, ['audit', 'block', 'all'], true)) { throw new \InvalidArgumentException( "Invalid 'apply' value for '{$id}': {$apply}. Expected 'audit', 'block', or 'all'." ); } } // Simple format with null: ['CVE-123' => null] elseif ($value === null) { $id = $key; $apply = 'all'; $reason = null; } else { continue; } // Store in appropriate lists based on apply scope if ($apply === 'audit' || $apply === 'all') { $forAudit[$id] = $reason; } if ($apply === 'block' || $apply === 'all') { $forBlock[$id] = $reason; } } return [ 'audit' => $forAudit, 'block' => $forBlock, ]; } /** * @param Auditor::FORMAT_* $auditFormat */ public static function fromConfig(Config $config, bool $audit = true, string $auditFormat = Auditor::FORMAT_SUMMARY): self { $auditConfig = $config->get('audit'); // Parse ignore lists with apply scopes $ignoreListParsed = self::parseIgnoreWithApply($auditConfig['ignore'] ?? []); $ignoreAbandonedParsed = self::parseIgnoreWithApply($auditConfig['ignore-abandoned'] ?? []); $ignoreSeverityParsed = self::parseIgnoreWithApply($auditConfig['ignore-severity'] ?? []); return new self( $audit, $auditFormat, $auditConfig['abandoned'] ?? Auditor::ABANDONED_FAIL, (bool) ($auditConfig['block-insecure'] ?? true), (bool) ($auditConfig['block-abandoned'] ?? false), (bool) ($auditConfig['ignore-unreachable'] ?? false), $ignoreListParsed['audit'], $ignoreListParsed['block'], $ignoreSeverityParsed['audit'], $ignoreSeverityParsed['block'], $ignoreAbandonedParsed['audit'], $ignoreAbandonedParsed['block'] ); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Advisory/SecurityAdvisory.php
src/Composer/Advisory/SecurityAdvisory.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\Advisory; use Composer\Semver\Constraint\ConstraintInterface; use DateTimeImmutable; class SecurityAdvisory extends PartialSecurityAdvisory { /** * @var string * @readonly */ public $title; /** * @var string|null * @readonly */ public $cve; /** * @var string|null * @readonly */ public $link; /** * @var DateTimeImmutable * @readonly */ public $reportedAt; /** * @var non-empty-array<array{name: string, remoteId: string}> * @readonly */ public $sources; /** * @var string|null * @readonly */ public $severity; /** * @param non-empty-array<array{name: string, remoteId: string}> $sources */ public function __construct(string $packageName, string $advisoryId, ConstraintInterface $affectedVersions, string $title, array $sources, DateTimeImmutable $reportedAt, ?string $cve = null, ?string $link = null, ?string $severity = null) { parent::__construct($packageName, $advisoryId, $affectedVersions); $this->title = $title; $this->sources = $sources; $this->reportedAt = $reportedAt; $this->cve = $cve; $this->link = $link; $this->severity = $severity; } /** * @internal */ public function toIgnoredAdvisory(?string $ignoreReason): IgnoredSecurityAdvisory { return new IgnoredSecurityAdvisory( $this->packageName, $this->advisoryId, $this->affectedVersions, $this->title, $this->sources, $this->reportedAt, $this->cve, $this->link, $ignoreReason, $this->severity ); } /** * @return mixed */ #[\ReturnTypeWillChange] public function jsonSerialize() { $data = parent::jsonSerialize(); $data['reportedAt'] = $data['reportedAt']->format(DATE_RFC3339); return $data; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Advisory/Auditor.php
src/Composer/Advisory/Auditor.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\Advisory; use Composer\IO\ConsoleIO; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\Package\BasePackage; use Composer\Package\CompletePackageInterface; use Composer\Package\PackageInterface; use Composer\Pcre\Preg; use Composer\Repository\RepositorySet; use Composer\Util\PackageInfo; use InvalidArgumentException; use Symfony\Component\Console\Formatter\OutputFormatter; /** * @internal */ class Auditor { public const FORMAT_TABLE = 'table'; public const FORMAT_PLAIN = 'plain'; public const FORMAT_JSON = 'json'; public const FORMAT_SUMMARY = 'summary'; public const FORMATS = [ self::FORMAT_TABLE, self::FORMAT_PLAIN, self::FORMAT_JSON, self::FORMAT_SUMMARY, ]; public const ABANDONED_IGNORE = 'ignore'; public const ABANDONED_REPORT = 'report'; public const ABANDONED_FAIL = 'fail'; /** @internal */ public const ABANDONEDS = [ self::ABANDONED_IGNORE, self::ABANDONED_REPORT, self::ABANDONED_FAIL, ]; /** Values to determine the audit result. */ public const STATUS_OK = 0; public const STATUS_VULNERABLE = 1; public const STATUS_ABANDONED = 2; /** * @param PackageInterface[] $packages * @param self::FORMAT_* $format The format that will be used to output audit results. * @param bool $warningOnly If true, outputs a warning. If false, outputs an error. * @param array<string, string|null> $ignoreList List of advisory IDs, remote IDs, CVE IDs or package names that reported but not listed as vulnerabilities. * @param self::ABANDONED_* $abandoned * @param array<string, string|null> $ignoredSeverities List of ignored severity levels * @param array<string, string|null> $ignoreAbandoned List of abandoned package name that reported but not listed as vulnerabilities. * * @return int-mask<self::STATUS_*> A bitmask of STATUS_* constants or 0 on success * @throws InvalidArgumentException If no packages are passed in */ public function audit(IOInterface $io, RepositorySet $repoSet, array $packages, string $format, bool $warningOnly = true, array $ignoreList = [], string $abandoned = self::ABANDONED_FAIL, array $ignoredSeverities = [], bool $ignoreUnreachable = false, array $ignoreAbandoned = []): int { $result = $repoSet->getMatchingSecurityAdvisories($packages, $format === self::FORMAT_SUMMARY, $ignoreUnreachable); $allAdvisories = $result['advisories']; $unreachableRepos = $result['unreachableRepos']; // we need the CVE & remote IDs set to filter ignores correctly so if we have any matches using the optimized codepath above // and ignores are set then we need to query again the full data to make sure it can be filtered if ($format === self::FORMAT_SUMMARY && $this->needsCompleteAdvisoryLoad($allAdvisories, $ignoreList)) { $result = $repoSet->getMatchingSecurityAdvisories($packages, false, $ignoreUnreachable); $allAdvisories = $result['advisories']; $unreachableRepos = array_merge($unreachableRepos, $result['unreachableRepos']); } ['advisories' => $advisories, 'ignoredAdvisories' => $ignoredAdvisories] = $this->processAdvisories($allAdvisories, $ignoreList, $ignoredSeverities); $abandonedCount = 0; $affectedPackagesCount = count($advisories); if ($abandoned === self::ABANDONED_IGNORE) { $abandonedPackages = []; } else { $abandonedPackages = $this->filterAbandonedPackages($packages, $ignoreAbandoned); if ($abandoned === self::ABANDONED_FAIL) { $abandonedCount = count($abandonedPackages); } } $auditBitmask = $this->calculateBitmask(0 < $affectedPackagesCount, 0 < $abandonedCount); if (self::FORMAT_JSON === $format) { $json = ['advisories' => $advisories]; if ($ignoredAdvisories !== []) { $json['ignored-advisories'] = $ignoredAdvisories; } if ($unreachableRepos !== []) { $json['unreachable-repositories'] = $unreachableRepos; } $json['abandoned'] = array_reduce($abandonedPackages, static function (array $carry, CompletePackageInterface $package): array { $carry[$package->getPrettyName()] = $package->getReplacementPackage(); return $carry; }, []); $io->write(JsonFile::encode($json)); return $auditBitmask; } $errorOrWarn = $warningOnly ? 'warning' : 'error'; if ($affectedPackagesCount > 0 || count($ignoredAdvisories) > 0) { $passes = [ [$ignoredAdvisories, "<info>Found %d ignored security vulnerability advisor%s affecting %d package%s%s</info>"], [$advisories, "<$errorOrWarn>Found %d security vulnerability advisor%s affecting %d package%s%s</$errorOrWarn>"], ]; foreach ($passes as [$advisoriesToOutput, $message]) { [$pkgCount, $totalAdvisoryCount] = $this->countAdvisories($advisoriesToOutput); if ($pkgCount > 0) { $plurality = $totalAdvisoryCount === 1 ? 'y' : 'ies'; $pkgPlurality = $pkgCount === 1 ? '' : 's'; $punctuation = $format === 'summary' ? '.' : ':'; $io->writeError(sprintf($message, $totalAdvisoryCount, $plurality, $pkgCount, $pkgPlurality, $punctuation)); $this->outputAdvisories($io, $advisoriesToOutput, $format); } } if ($format === self::FORMAT_SUMMARY) { $io->writeError('Run "composer audit" for a full list of advisories.'); } } else { $io->writeError('<info>No security vulnerability advisories found.</info>'); } if (count($unreachableRepos) > 0) { $io->writeError('<warning>The following repositories were unreachable:</warning>'); foreach ($unreachableRepos as $repo) { $io->writeError(' - ' . $repo); } } if (count($abandonedPackages) > 0 && $format !== self::FORMAT_SUMMARY) { $this->outputAbandonedPackages($io, $abandonedPackages, $format); } return $auditBitmask; } /** * @param array<string, array<SecurityAdvisory|PartialSecurityAdvisory>> $advisories * @param array<string, string|null> $ignoreList * @return bool */ public function needsCompleteAdvisoryLoad(array $advisories, array $ignoreList): bool { if (\count($advisories) === 0) { return false; } // no partial advisories present if (array_all($advisories, static function (array $pkgAdvisories) { return array_all($pkgAdvisories, static function ($advisory) { return $advisory instanceof SecurityAdvisory; }); })) { return false; } $ignoredIds = array_keys($ignoreList); return array_any($ignoredIds, static function (string $id) { return !str_starts_with($id, 'PKSA-'); }); } /** * @param array<PackageInterface> $packages * @param array<string, string|null> $ignoreAbandoned * @return array<CompletePackageInterface> */ public function filterAbandonedPackages(array $packages, array $ignoreAbandoned): array { $filter = null; if (\count($ignoreAbandoned) !== 0) { $filter = BasePackage::packageNamesToRegexp(array_keys($ignoreAbandoned)); } return array_filter($packages, static function (PackageInterface $pkg) use ($filter): bool { return $pkg instanceof CompletePackageInterface && $pkg->isAbandoned() && ($filter === null || !Preg::isMatch($filter, $pkg->getName())); }); } /** * @phpstan-param array<string, array<PartialSecurityAdvisory|SecurityAdvisory>> $allAdvisories * @param array<string, string|null> $ignoreList List of advisory IDs, remote IDs, CVE IDs or package names that reported but not listed as vulnerabilities. * @param array<string, string|null> $ignoredSeverities List of ignored severity levels * @phpstan-return array{advisories: array<string, array<PartialSecurityAdvisory|SecurityAdvisory>>, ignoredAdvisories: array<string, array<PartialSecurityAdvisory|SecurityAdvisory>>} */ public function processAdvisories(array $allAdvisories, array $ignoreList, array $ignoredSeverities): array { if ($ignoreList === [] && $ignoredSeverities === []) { return ['advisories' => $allAdvisories, 'ignoredAdvisories' => []]; } $advisories = []; $ignored = []; $ignoreReason = null; foreach ($allAdvisories as $package => $pkgAdvisories) { foreach ($pkgAdvisories as $advisory) { $isActive = true; if (array_key_exists($package, $ignoreList)) { $isActive = false; $ignoreReason = $ignoreList[$package] ?? null; } if (array_key_exists($advisory->advisoryId, $ignoreList)) { $isActive = false; $ignoreReason = $ignoreList[$advisory->advisoryId] ?? null; } if ($advisory instanceof SecurityAdvisory) { if (is_string($advisory->severity) && array_key_exists($advisory->severity, $ignoredSeverities)) { $isActive = false; $ignoreReason = $ignoredSeverities[$advisory->severity] ?? $advisory->severity.' severity is ignored'; } if (is_string($advisory->cve) && array_key_exists($advisory->cve, $ignoreList)) { $isActive = false; $ignoreReason = $ignoreList[$advisory->cve] ?? null; } foreach ($advisory->sources as $source) { if (array_key_exists($source['remoteId'], $ignoreList)) { $isActive = false; $ignoreReason = $ignoreList[$source['remoteId']] ?? null; break; } } } if ($isActive) { $advisories[$package][] = $advisory; continue; } // Partial security advisories only used in summary mode // and in that case we do not need to cast the object. if ($advisory instanceof SecurityAdvisory) { $advisory = $advisory->toIgnoredAdvisory($ignoreReason); } $ignored[$package][] = $advisory; } } return ['advisories' => $advisories, 'ignoredAdvisories' => $ignored]; } /** * @param array<string, array<PartialSecurityAdvisory>> $advisories * @return array{int, int} Count of affected packages and total count of advisories */ private function countAdvisories(array $advisories): array { $count = 0; foreach ($advisories as $packageAdvisories) { $count += count($packageAdvisories); } return [count($advisories), $count]; } /** * @param array<string, array<SecurityAdvisory>> $advisories * @param self::FORMAT_* $format The format that will be used to output audit results. */ private function outputAdvisories(IOInterface $io, array $advisories, string $format): void { switch ($format) { case self::FORMAT_TABLE: if (!($io instanceof ConsoleIO)) { throw new InvalidArgumentException('Cannot use table format with ' . get_class($io)); } $this->outputAdvisoriesTable($io, $advisories); return; case self::FORMAT_PLAIN: $this->outputAdvisoriesPlain($io, $advisories); return; case self::FORMAT_SUMMARY: return; default: throw new InvalidArgumentException('Invalid format "'.$format.'".'); } } /** * @param array<string, array<SecurityAdvisory>> $advisories */ private function outputAdvisoriesTable(ConsoleIO $io, array $advisories): void { foreach ($advisories as $packageAdvisories) { foreach ($packageAdvisories as $advisory) { $headers = [ 'Package', 'Severity', 'Advisory ID', 'CVE', 'Title', 'URL', 'Affected versions', 'Reported at', ]; $row = [ $advisory->packageName, $this->getSeverity($advisory), $this->getAdvisoryId($advisory), $this->getCVE($advisory), $advisory->title, $this->getURL($advisory), $advisory->affectedVersions->getPrettyString(), $advisory->reportedAt->format(DATE_ATOM), ]; if ($advisory instanceof IgnoredSecurityAdvisory) { $headers[] = 'Ignore reason'; $row[] = $advisory->ignoreReason ?? 'None specified'; } $io->getTable() ->setHorizontal() ->setHeaders($headers) ->addRow(ConsoleIO::sanitize($row)) ->setColumnWidth(1, 80) ->setColumnMaxWidth(1, 80) ->render(); } } } /** * @param array<string, array<SecurityAdvisory>> $advisories */ private function outputAdvisoriesPlain(IOInterface $io, array $advisories): void { $error = []; $firstAdvisory = true; foreach ($advisories as $packageAdvisories) { foreach ($packageAdvisories as $advisory) { if (!$firstAdvisory) { $error[] = '--------'; } $error[] = "Package: ".$advisory->packageName; $error[] = "Severity: ".$this->getSeverity($advisory); $error[] = "Advisory ID: ".$this->getAdvisoryId($advisory); $error[] = "CVE: ".$this->getCVE($advisory); $error[] = "Title: ".OutputFormatter::escape($advisory->title); $error[] = "URL: ".$this->getURL($advisory); $error[] = "Affected versions: ".OutputFormatter::escape($advisory->affectedVersions->getPrettyString()); $error[] = "Reported at: ".$advisory->reportedAt->format(DATE_ATOM); if ($advisory instanceof IgnoredSecurityAdvisory) { $error[] = "Ignore reason: ".($advisory->ignoreReason ?? 'None specified'); } $firstAdvisory = false; } } $io->writeError($error); } /** * @param array<CompletePackageInterface> $packages * @param self::FORMAT_PLAIN|self::FORMAT_TABLE $format */ private function outputAbandonedPackages(IOInterface $io, array $packages, string $format): void { $io->writeError(sprintf('<error>Found %d abandoned package%s:</error>', count($packages), count($packages) > 1 ? 's' : '')); if ($format === self::FORMAT_PLAIN) { foreach ($packages as $pkg) { $replacement = $pkg->getReplacementPackage() !== null ? 'Use '.$pkg->getReplacementPackage().' instead' : 'No replacement was suggested'; $io->writeError(sprintf( '%s is abandoned. %s.', $this->getPackageNameWithLink($pkg), $replacement )); } return; } if (!($io instanceof ConsoleIO)) { throw new InvalidArgumentException('Cannot use table format with ' . get_class($io)); } $table = $io->getTable() ->setHeaders(['Abandoned Package', 'Suggested Replacement']) ->setColumnWidth(1, 80) ->setColumnMaxWidth(1, 80); foreach ($packages as $pkg) { $replacement = $pkg->getReplacementPackage() !== null ? $pkg->getReplacementPackage() : 'none'; $table->addRow(ConsoleIO::sanitize([$this->getPackageNameWithLink($pkg), $replacement])); } $table->render(); } private function getPackageNameWithLink(PackageInterface $package): string { $packageUrl = PackageInfo::getViewSourceOrHomepageUrl($package); return $packageUrl !== null ? '<href=' . OutputFormatter::escape($packageUrl) . '>' . $package->getPrettyName() . '</>' : $package->getPrettyName(); } private function getSeverity(SecurityAdvisory $advisory): string { if ($advisory->severity === null) { return ''; } return $advisory->severity; } private function getAdvisoryId(SecurityAdvisory $advisory): string { if (str_starts_with($advisory->advisoryId, 'PKSA-')) { return '<href=https://packagist.org/security-advisories/'.$advisory->advisoryId.'>'.$advisory->advisoryId.'</>'; } return $advisory->advisoryId; } private function getCVE(SecurityAdvisory $advisory): string { if ($advisory->cve === null) { return 'NO CVE'; } return '<href=https://cve.mitre.org/cgi-bin/cvename.cgi?name='.$advisory->cve.'>'.$advisory->cve.'</>'; } private function getURL(SecurityAdvisory $advisory): string { if ($advisory->link === null) { return ''; } return '<href='.OutputFormatter::escape($advisory->link).'>'.OutputFormatter::escape($advisory->link).'</>'; } /** * @return int-mask<self::STATUS_*> */ private function calculateBitmask(bool $hasVulnerablePackages, bool $hasAbandonedPackages): int { $bitmask = self::STATUS_OK; if ($hasVulnerablePackages) { $bitmask |= self::STATUS_VULNERABLE; } if ($hasAbandonedPackages) { $bitmask |= self::STATUS_ABANDONED; } return $bitmask; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilter.php
src/Composer/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilter.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\Filter\PlatformRequirementFilter; use Composer\Repository\PlatformRepository; final class IgnoreAllPlatformRequirementFilter implements PlatformRequirementFilterInterface { public function isIgnored(string $req): bool { return PlatformRepository::isPlatformPackage($req); } public function isUpperBoundIgnored(string $req): bool { return $this->isIgnored($req); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilter.php
src/Composer/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilter.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\Filter\PlatformRequirementFilter; use Composer\Package\BasePackage; use Composer\Pcre\Preg; use Composer\Repository\PlatformRepository; use Composer\Semver\Constraint\Constraint; use Composer\Semver\Constraint\ConstraintInterface; use Composer\Semver\Constraint\MatchAllConstraint; use Composer\Semver\Constraint\MultiConstraint; use Composer\Semver\Interval; use Composer\Semver\Intervals; final class IgnoreListPlatformRequirementFilter implements PlatformRequirementFilterInterface { /** * @var non-empty-string */ private $ignoreRegex; /** * @var non-empty-string */ private $ignoreUpperBoundRegex; /** * @param string[] $reqList */ public function __construct(array $reqList) { $ignoreAll = $ignoreUpperBound = []; foreach ($reqList as $req) { if (substr($req, -1) === '+') { $ignoreUpperBound[] = substr($req, 0, -1); } else { $ignoreAll[] = $req; } } $this->ignoreRegex = BasePackage::packageNamesToRegexp($ignoreAll); $this->ignoreUpperBoundRegex = BasePackage::packageNamesToRegexp($ignoreUpperBound); } public function isIgnored(string $req): bool { if (!PlatformRepository::isPlatformPackage($req)) { return false; } return Preg::isMatch($this->ignoreRegex, $req); } public function isUpperBoundIgnored(string $req): bool { if (!PlatformRepository::isPlatformPackage($req)) { return false; } return $this->isIgnored($req) || Preg::isMatch($this->ignoreUpperBoundRegex, $req); } /** * @param bool $allowUpperBoundOverride For conflicts we do not want the upper bound to be skipped */ public function filterConstraint(string $req, ConstraintInterface $constraint, bool $allowUpperBoundOverride = true): ConstraintInterface { if (!PlatformRepository::isPlatformPackage($req)) { return $constraint; } if (!$allowUpperBoundOverride || !Preg::isMatch($this->ignoreUpperBoundRegex, $req)) { return $constraint; } if (Preg::isMatch($this->ignoreRegex, $req)) { return new MatchAllConstraint; } $intervals = Intervals::get($constraint); $last = end($intervals['numeric']); if ($last !== false && (string) $last->getEnd() !== (string) Interval::untilPositiveInfinity()) { $constraint = new MultiConstraint([$constraint, new Constraint('>=', $last->getEnd()->getVersion())], false); } return $constraint; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Filter/PlatformRequirementFilter/PlatformRequirementFilterFactory.php
src/Composer/Filter/PlatformRequirementFilter/PlatformRequirementFilterFactory.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\Filter\PlatformRequirementFilter; final class PlatformRequirementFilterFactory { /** * @param mixed $boolOrList */ public static function fromBoolOrList($boolOrList): PlatformRequirementFilterInterface { if (is_bool($boolOrList)) { return $boolOrList ? self::ignoreAll() : self::ignoreNothing(); } if (is_array($boolOrList)) { return new IgnoreListPlatformRequirementFilter($boolOrList); } throw new \InvalidArgumentException( sprintf( 'PlatformRequirementFilter: Unknown $boolOrList parameter %s. Please report at https://github.com/composer/composer/issues/new.', get_debug_type($boolOrList) ) ); } public static function ignoreAll(): PlatformRequirementFilterInterface { return new IgnoreAllPlatformRequirementFilter(); } public static function ignoreNothing(): PlatformRequirementFilterInterface { return new IgnoreNothingPlatformRequirementFilter(); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilter.php
src/Composer/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilter.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\Filter\PlatformRequirementFilter; final class IgnoreNothingPlatformRequirementFilter implements PlatformRequirementFilterInterface { /** * @return false */ public function isIgnored(string $req): bool { return false; } /** * @return false */ public function isUpperBoundIgnored(string $req): bool { return false; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Filter/PlatformRequirementFilter/PlatformRequirementFilterInterface.php
src/Composer/Filter/PlatformRequirementFilter/PlatformRequirementFilterInterface.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\Filter\PlatformRequirementFilter; interface PlatformRequirementFilterInterface { public function isIgnored(string $req): bool; public function isUpperBoundIgnored(string $req): bool; }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Json/JsonManipulator.php
src/Composer/Json/JsonManipulator.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\Json; use Composer\Pcre\Preg; use Composer\Repository\PlatformRepository; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class JsonManipulator { /** @var string */ private const DEFINES = '(?(DEFINE) (?<number> -? (?= [1-9]|0(?!\d) ) \d++ (?:\.\d++)? (?:[eE] [+-]?+ \d++)? ) (?<boolean> true | false | null ) (?<string> " (?:[^"\\\\]*+ | \\\\ ["\\\\bfnrt\/] | \\\\ u [0-9A-Fa-f]{4} )* " ) (?<array> \[ (?: (?&json) \s*+ (?: , (?&json) \s*+ )*+ )?+ \s*+ \] ) (?<pair> \s*+ (?&string) \s*+ : (?&json) \s*+ ) (?<object> \{ (?: (?&pair) (?: , (?&pair) )*+ )?+ \s*+ \} ) (?<json> \s*+ (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) ) ) )'; /** @var string */ private $contents; /** @var string */ private $newline; /** @var string */ private $indent; public function __construct(string $contents) { $contents = trim($contents); if ($contents === '') { $contents = '{}'; } if (!Preg::isMatch('#^\{(.*)\}$#s', $contents)) { throw new \InvalidArgumentException('The json file must be an object ({})'); } $this->newline = false !== strpos($contents, "\r\n") ? "\r\n" : "\n"; $this->contents = $contents === '{}' ? '{' . $this->newline . '}' : $contents; $this->detectIndenting(); } public function getContents(): string { return $this->contents . $this->newline; } public function addLink(string $type, string $package, string $constraint, bool $sortPackages = false): bool { $decoded = JsonFile::parseJson($this->contents); // no link of that type yet if (!isset($decoded[$type])) { return $this->addMainKey($type, [$package => $constraint]); } $regex = '{'.self::DEFINES.'^(?P<start>\s*\{\s*(?:(?&string)\s*:\s*(?&json)\s*,\s*)*?)'. '(?P<property>'.preg_quote(JsonFile::encode($type)).'\s*:\s*)(?P<value>(?&json))(?P<end>.*)}sx'; if (!Preg::isMatch($regex, $this->contents, $matches)) { return false; } assert(is_string($matches['start'])); assert(is_string($matches['value'])); assert(is_string($matches['end'])); $links = $matches['value']; // try to find existing link $packageRegex = str_replace('/', '\\\\?/', preg_quote($package)); $regex = '{'.self::DEFINES.'"(?P<package>'.$packageRegex.')"(\s*:\s*)(?&string)}ix'; if (Preg::isMatch($regex, $links, $packageMatches)) { assert(is_string($packageMatches['package'])); // update existing link $existingPackage = $packageMatches['package']; $packageRegex = str_replace('/', '\\\\?/', preg_quote($existingPackage)); $links = Preg::replaceCallback('{'.self::DEFINES.'"'.$packageRegex.'"(?P<separator>\s*:\s*)(?&string)}ix', static function ($m) use ($existingPackage, $constraint): string { return JsonFile::encode(str_replace('\\/', '/', $existingPackage)) . $m['separator'] . '"' . $constraint . '"'; }, $links); } else { if (Preg::isMatchStrictGroups('#^\s*\{\s*\S+.*?(\s*\}\s*)$#s', $links, $match)) { // link missing but non empty links $links = Preg::replace( '{'.preg_quote($match[1]).'$}', // addcslashes is used to double up backslashes/$ since preg_replace resolves them as back references otherwise, see #1588 addcslashes(',' . $this->newline . $this->indent . $this->indent . JsonFile::encode($package).': '.JsonFile::encode($constraint) . $match[1], '\\$'), $links ); } else { // links empty $links = '{' . $this->newline . $this->indent . $this->indent . JsonFile::encode($package).': '.JsonFile::encode($constraint) . $this->newline . $this->indent . '}'; } } if (true === $sortPackages) { $requirements = json_decode($links, true); $this->sortPackages($requirements); $links = $this->format($requirements); } $this->contents = $matches['start'] . $matches['property'] . $links . $matches['end']; return true; } /** * Sorts packages by importance (platform packages first, then PHP dependencies) and alphabetically. * * @link https://getcomposer.org/doc/02-libraries.md#platform-packages * * @param array<string> $packages */ private function sortPackages(array &$packages = []): void { $prefix = static function ($requirement): string { if (PlatformRepository::isPlatformPackage($requirement)) { return Preg::replace( [ '/^php/', '/^hhvm/', '/^ext/', '/^lib/', '/^\D/', ], [ '0-$0', '1-$0', '2-$0', '3-$0', '4-$0', ], $requirement ); } return '5-'.$requirement; }; uksort($packages, static function ($a, $b) use ($prefix): int { return strnatcmp($prefix($a), $prefix($b)); }); } /** * @param array<string, mixed>|false $config */ public function addRepository(string $name, $config, bool $append = true): bool { if ("" !== $name && !$this->doRemoveRepository($name)) { return false; } if (!$this->doConvertRepositoriesFromAssocToList()) { return false; } if (is_array($config) && !is_numeric($name) && '' !== $name) { $config = ['name' => $name] + $config; } elseif ($config === false) { $config = [$name => $config]; } return $this->addListItem('repositories', $config, $append); } private function doConvertRepositoriesFromAssocToList(): bool { $decoded = json_decode($this->contents, false); if (($decoded->repositories ?? null) instanceof \stdClass) { // delete from bottom to top, to ensure keys stay the same $entriesToRevert = array_reverse(array_keys((array) $decoded->repositories)); foreach ($entriesToRevert as $entryKey) { if (!$this->removeSubNode('repositories', (string) $entryKey)) { return false; } } $this->changeEmptyMainKeyFromAssocToList('repositories'); // re-add in order foreach (((array) $decoded->repositories) as $repositoryName => $repository) { if (!$repository instanceof \stdClass) { if (!$this->addListItem('repositories', [$repositoryName => $repository], true)) { return false; } } elseif (is_numeric($repositoryName)) { if (!$this->addListItem('repositories', $repository, true)) { return false; } } else { $repository = (array) $repository; // prepend name property $repository = ['name' => $repositoryName] + $repository; if (!$this->addListItem('repositories', $repository, true)) { return false; } } } } return true; } public function setRepositoryUrl(string $name, string $url): bool { $decoded = JsonFile::parseJson($this->contents); $repositoryIndex = null; foreach ($decoded['repositories'] ?? [] as $index => $repository) { if ($name === $index) { $repositoryIndex = $index; break; } if ($name === ($repository['name'] ?? null)) { $repositoryIndex = $index; break; } } if (null === $repositoryIndex) { return false; } $listRegex = null; if (is_int($repositoryIndex)) { $listRegex = '{'.self::DEFINES.'^(?P<start>\s*\{\s*(?:(?&string)\s*:\s*(?&json)\s*,\s*)*?"repositories"\s*:\s*\[\s*((?&json)\s*+,\s*+){' . max(0, $repositoryIndex) . '})(?P<repository>(?&object))(?P<end>.*)}sx'; } $objectRegex = '{'.self::DEFINES.'^(?P<start>\s*\{\s*(?:(?&string)\s*:\s*(?&json)\s*,\s*)*?"repositories"\s*:\s*\{\s*(?:(?&string)\s*:\s*(?&json)\s*,\s*)*?' . preg_quote(JsonFile::encode($repositoryIndex)) . '\s*:\s*)(?P<repository>(?&object))(?P<end>.*)}sx'; $matches = null; if (($listRegex !== null && Preg::isMatch($listRegex, $this->contents, $matches)) || Preg::isMatch($objectRegex, $this->contents, $matches)) { assert(isset($matches['start']) && is_string($matches['start'])); assert(isset($matches['repository']) && is_string($matches['repository'])); assert(isset($matches['end']) && is_string($matches['end'])); // invalid match due to un-regexable content, abort if (false === @json_decode($matches['repository'])) { return false; } $repositoryRegex = '{'.self::DEFINES.'^(?P<start>\s*\{\s*(?:(?&string)\s*:\s*(?&json)\s*,\s*)*?"url"\s*:\s*)(?P<url>(?&string))(?P<end>.*)}sx'; $this->contents = $matches['start'] . Preg::replaceCallback($repositoryRegex, static function (array $repositoryMatches) use ($url): string { return $repositoryMatches['start'] . JsonFile::encode($url) . $repositoryMatches['end']; }, $matches['repository']) . $matches['end']; return true; } return false; } /** * @param array<string, mixed>|false $config */ public function insertRepository(string $name, $config, string $referenceName, int $offset = 0): bool { if ("" !== $name && !$this->doRemoveRepository($name)) { return false; } if (!$this->doConvertRepositoriesFromAssocToList()) { return false; } $indexToInsert = null; $decoded = JsonFile::parseJson($this->contents); foreach ($decoded['repositories'] as $repositoryIndex => $repository) { if (($repository['name'] ?? null) === $referenceName) { $indexToInsert = $repositoryIndex; break; } if ($repositoryIndex === $referenceName) { $indexToInsert = $repositoryIndex; break; } if ([$referenceName => false] === $repository) { $indexToInsert = $repositoryIndex; break; } } if ($indexToInsert === null) { return false; } if (is_array($config) && !is_numeric($name) && '' !== $name) { $config = ['name' => $name] + $config; } elseif ($config === false) { $config = ['name' => $config]; } return $this->insertListItem('repositories', $config, $indexToInsert + $offset); } public function removeRepository(string $name): bool { return $this->doRemoveRepository($name) && $this->removeMainKeyIfEmpty('repositories'); } private function doRemoveRepository(string $name): bool { $decoded = json_decode($this->contents, false); $isAssoc = ($decoded->repositories ?? null) instanceof \stdClass; foreach ((array) ($decoded->repositories ?? []) as $repositoryIndex => $repository) { if ($repositoryIndex === $name && $isAssoc) { if (!$this->removeSubNode('repositories', $repositoryIndex)) { return false; } break; } if (($repository->name ?? null) === $name) { if ($isAssoc) { if (!$this->removeSubNode('repositories', (string) $repositoryIndex)) { return false; } } else { if (!$this->removeListItem('repositories', (int) $repositoryIndex)) { return false; } } break; } if ($isAssoc) { if ($name === $repositoryIndex && false === $repository) { if (!$this->removeSubNode('repositories', $repositoryIndex)) { return false; } return true; } } else { $repositoryAsArray = (array) $repository; if (false === ($repositoryAsArray[$name] ?? null) && 1 === count($repositoryAsArray)) { if (!$this->removeListItem('repositories', (int) $repositoryIndex)) { return false; } return true; } } } return true; } /** * @param mixed $value */ public function addConfigSetting(string $name, $value): bool { return $this->addSubNode('config', $name, $value); } public function removeConfigSetting(string $name): bool { return $this->removeSubNode('config', $name); } /** * @param mixed $value */ public function addProperty(string $name, $value): bool { if (strpos($name, 'suggest.') === 0) { return $this->addSubNode('suggest', substr($name, 8), $value); } if (strpos($name, 'extra.') === 0) { return $this->addSubNode('extra', substr($name, 6), $value); } if (strpos($name, 'scripts.') === 0) { return $this->addSubNode('scripts', substr($name, 8), $value); } return $this->addMainKey($name, $value); } public function removeProperty(string $name): bool { if (strpos($name, 'suggest.') === 0) { return $this->removeSubNode('suggest', substr($name, 8)); } if (strpos($name, 'extra.') === 0) { return $this->removeSubNode('extra', substr($name, 6)); } if (strpos($name, 'scripts.') === 0) { return $this->removeSubNode('scripts', substr($name, 8)); } if (strpos($name, 'autoload.') === 0) { return $this->removeSubNode('autoload', substr($name, 9)); } if (strpos($name, 'autoload-dev.') === 0) { return $this->removeSubNode('autoload-dev', substr($name, 13)); } return $this->removeMainKey($name); } /** * @param mixed $value */ public function addSubNode(string $mainNode, string $name, $value, bool $append = true): bool { $decoded = JsonFile::parseJson($this->contents); $subName = null; if (in_array($mainNode, ['config', 'extra', 'scripts']) && false !== strpos($name, '.')) { [$name, $subName] = explode('.', $name, 2); } // no main node yet if (!isset($decoded[$mainNode])) { if ($subName !== null) { $this->addMainKey($mainNode, [$name => [$subName => $value]]); } else { $this->addMainKey($mainNode, [$name => $value]); } return true; } // main node content not match-able $nodeRegex = '{'.self::DEFINES.'^(?P<start> \s* \{ \s* (?: (?&string) \s* : (?&json) \s* , \s* )*?'. preg_quote(JsonFile::encode($mainNode)).'\s*:\s*)(?P<content>(?&object))(?P<end>.*)}sx'; try { if (!Preg::isMatch($nodeRegex, $this->contents, $match)) { return false; } } catch (\RuntimeException $e) { if ($e->getCode() === PREG_BACKTRACK_LIMIT_ERROR) { return false; } throw $e; } assert(is_string($match['start'])); assert(is_string($match['content'])); assert(is_string($match['end'])); $children = $match['content']; // invalid match due to un-regexable content, abort if (!@json_decode($children)) { return false; } // child exists $childRegex = '{'.self::DEFINES.'(?P<start>"'.preg_quote($name).'"\s*:\s*)(?P<content>(?&json))(?P<end>,?)}x'; if (Preg::isMatch($childRegex, $children, $matches)) { $children = Preg::replaceCallback($childRegex, function ($matches) use ($subName, $value): string { if ($subName !== null && is_string($matches['content'])) { $curVal = json_decode($matches['content'], true); if (!is_array($curVal)) { $curVal = []; } $curVal[$subName] = $value; $value = $curVal; } return $matches['start'] . $this->format($value, 1) . $matches['end']; }, $children); } elseif (Preg::isMatch('#^\{(?P<leadingspace>\s*?)(?P<content>\S+.*?)?(?P<trailingspace>\s*)\}$#s', $children, $match)) { $whitespace = $match['trailingspace']; if (null !== $match['content']) { if ($subName !== null) { $value = [$subName => $value]; } // child missing but non empty children if ($append) { $children = Preg::replace( '#'.$whitespace.'}$#', addcslashes(',' . $this->newline . $this->indent . $this->indent . JsonFile::encode($name).': '.$this->format($value, 1) . $whitespace . '}', '\\$'), $children ); } else { $whitespace = $match['leadingspace']; $children = Preg::replace( '#^{'.$whitespace.'#', addcslashes('{' . $whitespace . JsonFile::encode($name).': '.$this->format($value, 1) . ',' . $this->newline . $this->indent . $this->indent, '\\$'), $children ); } } else { if ($subName !== null) { $value = [$subName => $value]; } // children present but empty $children = '{' . $this->newline . $this->indent . $this->indent . JsonFile::encode($name).': '.$this->format($value, 1) . $whitespace . '}'; } } else { throw new \LogicException('Nothing matched above for: '.$children); } $this->contents = Preg::replaceCallback($nodeRegex, static function ($m) use ($children): string { return $m['start'] . $children . $m['end']; }, $this->contents); return true; } public function removeSubNode(string $mainNode, string $name): bool { $decoded = JsonFile::parseJson($this->contents); // no node or empty node if (empty($decoded[$mainNode])) { return true; } // no node content match-able $nodeRegex = '{'.self::DEFINES.'^(?P<start> \s* \{ \s* (?: (?&string) \s* : (?&json) \s* , \s* )*?'. preg_quote(JsonFile::encode($mainNode)).'\s*:\s*)(?P<content>(?&object))(?P<end>.*)}sx'; try { if (!Preg::isMatch($nodeRegex, $this->contents, $match)) { return false; } } catch (\RuntimeException $e) { if ($e->getCode() === PREG_BACKTRACK_LIMIT_ERROR) { return false; } throw $e; } assert(is_string($match['start'])); assert(is_string($match['content'])); assert(is_string($match['end'])); $children = $match['content']; // invalid match due to un-regexable content, abort if (!@json_decode($children, true)) { return false; } $subName = null; if (in_array($mainNode, ['config', 'extra', 'scripts']) && false !== strpos($name, '.')) { [$name, $subName] = explode('.', $name, 2); } // no node to remove if (!isset($decoded[$mainNode][$name]) || ($subName && !isset($decoded[$mainNode][$name][$subName]))) { return true; } // try and find a match for the subkey $keyRegex = str_replace('/', '\\\\?/', preg_quote($name)); if (Preg::isMatch('{"'.$keyRegex.'"\s*:}i', $children)) { // find best match for the value of "name" if (Preg::isMatchAll('{'.self::DEFINES.'"'.$keyRegex.'"\s*:\s*(?:(?&json))}x', $children, $matches)) { $bestMatch = ''; foreach ($matches[0] as $match) { assert(is_string($match)); if (strlen($bestMatch) < strlen($match)) { $bestMatch = $match; } } $childrenClean = Preg::replace('{,\s*'.preg_quote($bestMatch).'}i', '', $children, -1, $count); if (1 !== $count) { $childrenClean = Preg::replace('{'.preg_quote($bestMatch).'\s*,?\s*}i', '', $childrenClean, -1, $count); if (1 !== $count) { return false; } } } } else { $childrenClean = $children; } if (!isset($childrenClean)) { throw new \InvalidArgumentException("JsonManipulator: \$childrenClean is not defined. Please report at https://github.com/composer/composer/issues/new."); } // no child data left, $name was the only key in unset($match); if (Preg::isMatch('#^\{\s*?(?P<content>\S+.*?)?(?P<trailingspace>\s*)\}$#s', $childrenClean, $match)) { if (null === $match['content']) { $newline = $this->newline; $indent = $this->indent; $this->contents = Preg::replaceCallback($nodeRegex, static function ($matches) use ($indent, $newline): string { return $matches['start'] . '{' . $newline . $indent . '}' . $matches['end']; }, $this->contents); // we have a subname, so we restore the rest of $name if ($subName !== null) { $curVal = json_decode($children, true); unset($curVal[$name][$subName]); if ($curVal[$name] === []) { $curVal[$name] = new \ArrayObject(); } $this->addSubNode($mainNode, $name, $curVal[$name]); } return true; } } $this->contents = Preg::replaceCallback($nodeRegex, function ($matches) use ($name, $subName, $childrenClean): string { assert(is_string($matches['content'])); if ($subName !== null) { $curVal = json_decode($matches['content'], true); unset($curVal[$name][$subName]); if ($curVal[$name] === []) { $curVal[$name] = new \ArrayObject(); } $childrenClean = $this->format($curVal, 0, true); } return $matches['start'] . $childrenClean . $matches['end']; }, $this->contents); return true; } /** * @param mixed $value */ public function addListItem(string $mainNode, $value, bool $append = true): bool { $decoded = JsonFile::parseJson($this->contents); // no main node yet if (!isset($decoded[$mainNode])) { if (!$this->addMainKey($mainNode, [])) { return false; } } // main node content not match-able $nodeRegex = '{'.self::DEFINES.'^(?P<start> \s* \{ \s* (?: (?&string) \s* : (?&json) \s* , \s* )*?'. preg_quote(JsonFile::encode($mainNode)).'\s*:\s*)(?P<content>(?&array))(?P<end>.*)}sx'; try { if (!Preg::isMatch($nodeRegex, $this->contents, $match)) { return false; } } catch (\RuntimeException $e) { if ($e->getCode() === PREG_BACKTRACK_LIMIT_ERROR) { return false; } throw $e; } assert(is_string($match['start'])); assert(is_string($match['content'])); assert(is_string($match['end'])); $children = $match['content']; // invalid match due to un-regexable content, abort if (false === @json_decode($children)) { return false; } if (Preg::isMatch('#^\[(?P<leadingspace>\s*?)(?P<content>\S+.*?)?(?P<trailingspace>\s*)\]$#s', $children, $match)) { $leadingWhitespace = $match['leadingspace']; $whitespace = $match['trailingspace']; $leadingItemWhitespace = $this->newline . $this->indent . $this->indent; $trailingItemWhitespace = $whitespace; $itemDepth = 1; // keep oneline lists as one line if (!str_contains($whitespace, $this->newline)) { $leadingItemWhitespace = $leadingWhitespace; $trailingItemWhitespace = $leadingWhitespace; $itemDepth = 0; } if (null !== $match['content']) { // child missing but non empty children if ($append) { $children = Preg::replace( '#'.$whitespace.']$#', addcslashes(',' . $leadingItemWhitespace . $this->format($value, $itemDepth) . $trailingItemWhitespace . ']', '\\$'), $children ); } else { $whitespace = $match['leadingspace']; $children = Preg::replace( '#^\['.$whitespace.'#', addcslashes('[' . $whitespace . $this->format($value, $itemDepth) . ',' . $leadingItemWhitespace, '\\$'), $children ); } } else { // children present but empty $children = '[' . $leadingItemWhitespace . $this->format($value, $itemDepth) . $trailingItemWhitespace . ']'; } } else { throw new \LogicException('Nothing matched above for: '.$children); } $this->contents = Preg::replaceCallback($nodeRegex, static function ($m) use ($children): string { return $m['start'] . $children . $m['end']; }, $this->contents); return true; } /** * @param mixed $value */ public function insertListItem(string $mainNode, $value, int $index): bool { if ($index < 0) { throw new \InvalidArgumentException('Index can only be positive integer'); } if ($index === 0) { return $this->addListItem($mainNode, $value, false); } $decoded = JsonFile::parseJson($this->contents); // no main node yet if (!isset($decoded[$mainNode])) { if (!$this->addMainKey($mainNode, [])) { return false; } } if (count($decoded[$mainNode]) === $index) { return $this->addListItem($mainNode, $value, true); } // main node content not match-able $nodeRegex = '{'.self::DEFINES.'^(?P<start> \s* \{ \s* (?: (?&string) \s* : (?&json) \s* , \s* )*?'. preg_quote(JsonFile::encode($mainNode)).'\s*:\s*)(?P<content>(?&array))(?P<end>.*)}sx'; try { if (!Preg::isMatch($nodeRegex, $this->contents, $match)) { return false; } } catch (\RuntimeException $e) { if ($e->getCode() === PREG_BACKTRACK_LIMIT_ERROR) { return false; } throw $e; } assert(is_string($match['start'])); assert(is_string($match['content'])); assert(is_string($match['end'])); $children = $match['content']; // invalid match due to un-regexable content, abort if (false === @json_decode($children)) { return false; } $listSkipToItemRegex = '{'.self::DEFINES.'^(?P<start>\[\s*((?&json)\s*+,\s*?){' . max(0, $index) . '})(?P<space_before_item>(\s*))(?P<end>.*)}sx'; $children = Preg::replaceCallback($listSkipToItemRegex, function ($m) use ($value): string { return $m['start'] . $m['space_before_item'] . $this->format($value, 1) . ',' . $m['space_before_item'] . $m['end']; }, $children); $this->contents = Preg::replaceCallback($nodeRegex, static function ($m) use ($children): string { return $m['start'] . $children . $m['end']; }, $this->contents); return true; } public function removeListItem(string $mainNode, int $nodeIndex): bool { // invalid index, that cannot be removed anyway if ($nodeIndex < 0) { return true; } $decoded = JsonFile::parseJson($this->contents); // no node or empty node if ([] === $decoded[$mainNode]) { return true; } // no node content match-able $nodeRegex = '{'.self::DEFINES.'^(?P<start> \s* \{ \s* (?: (?&string) \s* : (?&json) \s* , \s* )*?'. preg_quote(JsonFile::encode($mainNode)).'\s*:\s*)(?P<content>(?&array))(?P<end>.*)}sx'; try { if (!Preg::isMatch($nodeRegex, $this->contents, $match)) { return false; } } catch (\RuntimeException $e) { if ($e->getCode() === PREG_BACKTRACK_LIMIT_ERROR) { return false; } throw $e; } assert(is_string($match['start'])); assert(is_string($match['content'])); assert(is_string($match['end'])); $children = $match['content']; // invalid match due to un-regexable content, abort if (false === @json_decode($children, true)) { return false; } // no node to remove if (!isset($decoded[$mainNode][$nodeIndex])) { return true; } $contentRegex = '(?&json)'; if ($nodeIndex > 1) { $startRegex = '(?&json)\s*+(?:,(?&json)\s*+){' . ($nodeIndex - 1) . '}'; // remove leading array separator in case we might remove the last $contentRegex = '\s*+,?\s*+' . $contentRegex; $endRegex = '(?:(\s*+,\s*+(?&json))*(?:\s*+(?&json))?)\s*+'; } elseif ($nodeIndex > 0) { $startRegex = '(?&json)\s*+'; // remove leading array separator in case we might remove the last $contentRegex = '\s*+,?\s*+' . $contentRegex; $endRegex = '(?:(\s*+,\s*+(?&json))*(?:\s*+(?&json))?)\s*+'; } else { $startRegex = '\s*+'; // remove trailing array separator when we delete first $contentRegex = $contentRegex . '\s*+,?\s*+'; $endRegex = '(?:((?&json)\s*+,\s*+)*(?:\s*+(?&json))?)\s*+'; } if (Preg::isMatch('{'.self::DEFINES.'(?P<start>\[' . $startRegex . ')(?P<content>' . $contentRegex . ')(?P<end>' . $endRegex . '\])}sx', $children, $childMatch)) { $this->contents = $match['start'] . $childMatch['start'] . $childMatch['end'] . $match['end']; return true; } return false; } /** * @param mixed $content */ public function addMainKey(string $key, $content): bool { $decoded = JsonFile::parseJson($this->contents); $content = $this->format($content); // key exists already $regex = '{'.self::DEFINES.'^(?P<start>\s*\{\s*(?:(?&string)\s*:\s*(?&json)\s*,\s*)*?)'. '(?P<key>'.preg_quote(JsonFile::encode($key)).'\s*:\s*(?&json))(?P<end>.*)}sx';
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
true
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Json/JsonFile.php
src/Composer/Json/JsonFile.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\Json; use Composer\Pcre\Preg; use Composer\Util\Filesystem; use JsonSchema\Validator; use Seld\JsonLint\JsonParser; use Seld\JsonLint\ParsingException; use Composer\Util\HttpDownloader; use Composer\IO\IOInterface; use Composer\Downloader\TransportException; /** * Reads/writes json files. * * @author Konstantin Kudryashiv <ever.zet@gmail.com> * @author Jordi Boggiano <j.boggiano@seld.be> */ class JsonFile { public const LAX_SCHEMA = 1; public const STRICT_SCHEMA = 2; public const AUTH_SCHEMA = 3; public const LOCK_SCHEMA = 4; /** @deprecated Use \JSON_UNESCAPED_SLASHES */ public const JSON_UNESCAPED_SLASHES = 64; /** @deprecated Use \JSON_PRETTY_PRINT */ public const JSON_PRETTY_PRINT = 128; /** @deprecated Use \JSON_UNESCAPED_UNICODE */ public const JSON_UNESCAPED_UNICODE = 256; public const COMPOSER_SCHEMA_PATH = __DIR__ . '/../../../res/composer-schema.json'; public const LOCK_SCHEMA_PATH = __DIR__ . '/../../../res/composer-lock-schema.json'; public const INDENT_DEFAULT = ' '; /** @var string */ private $path; /** @var ?HttpDownloader */ private $httpDownloader; /** @var ?IOInterface */ private $io; /** @var string */ private $indent = self::INDENT_DEFAULT; /** * Initializes json file reader/parser. * * @param string $path path to a lockfile * @param ?HttpDownloader $httpDownloader required for loading http/https json files * @throws \InvalidArgumentException */ public function __construct(string $path, ?HttpDownloader $httpDownloader = null, ?IOInterface $io = null) { $this->path = $path; if (null === $httpDownloader && Preg::isMatch('{^https?://}i', $path)) { throw new \InvalidArgumentException('http urls require a HttpDownloader instance to be passed'); } $this->httpDownloader = $httpDownloader; $this->io = $io; } public function getPath(): string { return $this->path; } /** * Checks whether json file exists. */ public function exists(): bool { return is_file($this->path); } /** * Reads json file. * * @throws ParsingException * @throws \RuntimeException * @return mixed */ public function read() { try { if ($this->httpDownloader) { $json = $this->httpDownloader->get($this->path)->getBody(); } else { if (!Filesystem::isReadable($this->path)) { throw new \RuntimeException('The file "'.$this->path.'" is not readable.'); } if ($this->io && $this->io->isDebug()) { $realpathInfo = ''; $realpath = realpath($this->path); if (false !== $realpath && $realpath !== $this->path) { $realpathInfo = ' (' . $realpath . ')'; } $this->io->writeError('Reading ' . $this->path . $realpathInfo); } $json = file_get_contents($this->path); } } catch (TransportException $e) { throw new \RuntimeException($e->getMessage(), 0, $e); } catch (\Exception $e) { throw new \RuntimeException('Could not read '.$this->path."\n\n".$e->getMessage()); } if ($json === false) { throw new \RuntimeException('Could not read '.$this->path); } $this->indent = self::detectIndenting($json); return static::parseJson($json, $this->path); } /** * Writes json file. * * @param mixed[] $hash writes hash into json file * @param int $options json_encode options * @throws \UnexpectedValueException|\Exception * @return void */ public function write(array $hash, int $options = JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) { if ($this->path === 'php://memory') { file_put_contents($this->path, static::encode($hash, $options, $this->indent)); return; } $dir = dirname($this->path); if (!is_dir($dir)) { if (file_exists($dir)) { throw new \UnexpectedValueException( realpath($dir).' exists and is not a directory.' ); } if (!@mkdir($dir, 0777, true)) { throw new \UnexpectedValueException( $dir.' does not exist and could not be created.' ); } } $retries = 3; while ($retries--) { try { $this->filePutContentsIfModified($this->path, static::encode($hash, $options, $this->indent). ($options & JSON_PRETTY_PRINT ? "\n" : '')); break; } catch (\Exception $e) { if ($retries > 0) { usleep(500000); continue; } throw $e; } } } /** * Modify file properties only if content modified * * @return int|false */ private function filePutContentsIfModified(string $path, string $content) { $currentContent = @file_get_contents($path); if (false === $currentContent || $currentContent !== $content) { return file_put_contents($path, $content); } return 0; } /** * Validates the schema of the current json file according to composer-schema.json rules * * @param int $schema a JsonFile::*_SCHEMA constant * @param string|null $schemaFile a path to the schema file * @throws JsonValidationException * @throws ParsingException * @return true true on success * * @phpstan-param self::*_SCHEMA $schema */ public function validateSchema(int $schema = self::STRICT_SCHEMA, ?string $schemaFile = null): bool { if (!Filesystem::isReadable($this->path)) { throw new \RuntimeException('The file "'.$this->path.'" is not readable.'); } $content = file_get_contents($this->path); $data = json_decode($content); if (null === $data && 'null' !== $content) { self::validateSyntax($content, $this->path); } return self::validateJsonSchema($this->path, $data, $schema, $schemaFile); } /** * Validates the schema of the current json file according to composer-schema.json rules * * @param mixed $data Decoded JSON data to validate * @param int $schema a JsonFile::*_SCHEMA constant * @param string|null $schemaFile a path to the schema file * @throws JsonValidationException * @return true true on success * * @phpstan-param self::*_SCHEMA $schema */ public static function validateJsonSchema(string $source, $data, int $schema, ?string $schemaFile = null): bool { $isComposerSchemaFile = false; if (null === $schemaFile) { if ($schema === self::LOCK_SCHEMA) { $schemaFile = self::LOCK_SCHEMA_PATH; } else { $isComposerSchemaFile = true; $schemaFile = self::COMPOSER_SCHEMA_PATH; } } // Prepend with file:// only when not using a special schema already (e.g. in the phar) if (false === strpos($schemaFile, '://')) { $schemaFile = 'file://' . $schemaFile; } $schemaData = (object) ['$ref' => $schemaFile, '$schema' => "https://json-schema.org/draft-04/schema#"]; if ($schema === self::STRICT_SCHEMA && $isComposerSchemaFile) { $schemaData = json_decode((string) file_get_contents($schemaFile)); $schemaData->additionalProperties = false; $schemaData->required = ['name', 'description']; } elseif ($schema === self::AUTH_SCHEMA && $isComposerSchemaFile) { $schemaData = (object) ['$ref' => $schemaFile.'#/properties/config', '$schema' => "https://json-schema.org/draft-04/schema#"]; } $validator = new Validator(); // convert assoc arrays to objects $data = json_decode((string) json_encode($data)); $validator->validate($data, $schemaData); if (!$validator->isValid()) { $errors = []; foreach ($validator->getErrors() as $error) { $errors[] = ($error['property'] ? $error['property'].' : ' : '').$error['message']; } throw new JsonValidationException('"'.$source.'" does not match the expected JSON schema', $errors); } return true; } /** * Encodes an array into (optionally pretty-printed) JSON * * @param mixed $data Data to encode into a formatted JSON string * @param int $options json_encode options (defaults to JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) * @param string $indent Indentation string * @return string Encoded json */ public static function encode($data, int $options = \JSON_UNESCAPED_SLASHES | \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE, string $indent = self::INDENT_DEFAULT): string { $json = json_encode($data, $options); if (false === $json) { self::throwEncodeError(json_last_error()); } if (($options & JSON_PRETTY_PRINT) > 0 && $indent !== self::INDENT_DEFAULT) { // Pretty printing and not using default indentation return Preg::replaceCallback( '#^ {4,}#m', static function ($match) use ($indent): string { return str_repeat($indent, (int) (strlen($match[0]) / 4)); }, $json ); } return $json; } /** * Throws an exception according to a given code with a customized message * * @param int $code return code of json_last_error function * @throws \RuntimeException * @return never */ private static function throwEncodeError(int $code): void { switch ($code) { case JSON_ERROR_DEPTH: $msg = 'Maximum stack depth exceeded'; break; case JSON_ERROR_STATE_MISMATCH: $msg = 'Underflow or the modes mismatch'; break; case JSON_ERROR_CTRL_CHAR: $msg = 'Unexpected control character found'; break; case JSON_ERROR_UTF8: $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded'; break; default: $msg = 'Unknown error'; } throw new \RuntimeException('JSON encoding failed: '.$msg); } /** * Parses json string and returns hash. * * @param null|string $json json string * @param string $file the json file * * @throws ParsingException * @return mixed */ public static function parseJson(?string $json, ?string $file = null) { if (null === $json) { return null; } $data = json_decode($json, true); if (null === $data && JSON_ERROR_NONE !== json_last_error()) { // attempt resolving simple conflicts in lock files so that one can run `composer update --lock` and get a valid lock file if ($file !== null && str_ends_with($file, '.lock') && str_contains($json, '"content-hash"')) { $replaced = Preg::replace( '{\r?\n<<<<<<< [^\r\n]+\r?\n\s+"content-hash": *"[0-9a-f]+", *\r?\n(?:\|{7} [^\r\n]+\r?\n\s+"content-hash": *"[0-9a-f]+", *\r?\n)?=======\r?\n\s+"content-hash": *"[0-9a-f]+", *\r?\n>>>>>>> [^\r\n]+(\r?\n)}', ' "content-hash": "VCS merge conflict detected. Please run `composer update --lock`.",$1', $json, 1, $count ); if ($count === 1) { $data = json_decode($replaced, true); if ($data !== null) { return $data; } } } self::validateSyntax($json, $file); } return $data; } /** * Validates the syntax of a JSON string * * @throws \UnexpectedValueException * @throws ParsingException * @return bool true on success */ protected static function validateSyntax(string $json, ?string $file = null): bool { $parser = new JsonParser(); $result = $parser->lint($json); if (null === $result) { if (defined('JSON_ERROR_UTF8') && JSON_ERROR_UTF8 === json_last_error()) { if ($file === null) { throw new \UnexpectedValueException('The input is not UTF-8, could not parse as JSON'); } else { throw new \UnexpectedValueException('"' . $file . '" is not UTF-8, could not parse as JSON'); } } return true; } if ($file === null) { throw new ParsingException( 'The input does not contain valid JSON' . "\n" . $result->getMessage(), $result->getDetails() ); } else { throw new ParsingException( '"' . $file . '" does not contain valid JSON' . "\n" . $result->getMessage(), $result->getDetails() ); } } public static function detectIndenting(?string $json): string { if (Preg::isMatchStrictGroups('#^([ \t]+)"#m', $json ?? '', $match)) { return $match[1]; } return self::INDENT_DEFAULT; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Json/JsonFormatter.php
src/Composer/Json/JsonFormatter.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\Json; use Composer\Pcre\Preg; /** * Formats json strings used for php < 5.4 because the json_encode doesn't * supports the flags JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE * in these versions * * @author Konstantin Kudryashiv <ever.zet@gmail.com> * @author Jordi Boggiano <j.boggiano@seld.be> * * @deprecated Use json_encode or JsonFile::encode() with modern JSON_* flags to configure formatting - this class will be removed in 3.0 */ class JsonFormatter { /** * This code is based on the function found at: * http://recursive-design.com/blog/2008/03/11/format-json-with-php/ * * Originally licensed under MIT by Dave Perrett <mail@recursive-design.com> * * @param bool $unescapeUnicode Un escape unicode * @param bool $unescapeSlashes Un escape slashes */ public static function format(string $json, bool $unescapeUnicode, bool $unescapeSlashes): string { $result = ''; $pos = 0; $strLen = strlen($json); $indentStr = ' '; $newLine = "\n"; $outOfQuotes = true; $buffer = ''; $noescape = true; for ($i = 0; $i < $strLen; $i++) { // Grab the next character in the string $char = substr($json, $i, 1); // Are we inside a quoted string? if ('"' === $char && $noescape) { $outOfQuotes = !$outOfQuotes; } if (!$outOfQuotes) { $buffer .= $char; $noescape = '\\' === $char ? !$noescape : true; continue; } if ('' !== $buffer) { if ($unescapeSlashes) { $buffer = str_replace('\\/', '/', $buffer); } if ($unescapeUnicode && function_exists('mb_convert_encoding')) { // https://stackoverflow.com/questions/2934563/how-to-decode-unicode-escape-sequences-like-u00ed-to-proper-utf-8-encoded-cha $buffer = Preg::replaceCallback('/(\\\\+)u([0-9a-f]{4})/i', static function ($match): string { $l = strlen($match[1]); if ($l % 2) { $code = hexdec($match[2]); // 0xD800..0xDFFF denotes UTF-16 surrogate pair which won't be unescaped // see https://github.com/composer/composer/issues/7510 if (0xD800 <= $code && 0xDFFF >= $code) { return $match[0]; } return str_repeat('\\', $l - 1) . mb_convert_encoding( pack('H*', $match[2]), 'UTF-8', 'UCS-2BE' ); } return $match[0]; }, $buffer); } $result .= $buffer.$char; $buffer = ''; continue; } if (':' === $char) { // Add a space after the : character $char .= ' '; } elseif ('}' === $char || ']' === $char) { $pos--; $prevChar = substr($json, $i - 1, 1); if ('{' !== $prevChar && '[' !== $prevChar) { // If this character is the end of an element, // output a new line and indent the next line $result .= $newLine; $result .= str_repeat($indentStr, $pos); } else { // Collapse empty {} and [] $result = rtrim($result); } } $result .= $char; // If the last character was the beginning of an element, // output a new line and indent the next line if (',' === $char || '{' === $char || '[' === $char) { $result .= $newLine; if ('{' === $char || '[' === $char) { $pos++; } $result .= str_repeat($indentStr, $pos); } } return $result; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Json/JsonValidationException.php
src/Composer/Json/JsonValidationException.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\Json; use Exception; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class JsonValidationException extends Exception { /** * @var string[] */ protected $errors; /** * @param string[] $errors */ public function __construct(string $message, array $errors = [], ?Exception $previous = null) { $this->errors = $errors; parent::__construct((string) $message, 0, $previous); } /** * @return string[] */ public function getErrors(): array { return $this->errors; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Question/StrictConfirmationQuestion.php
src/Composer/Question/StrictConfirmationQuestion.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\Question; use Composer\Pcre\Preg; use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Question\Question; /** * Represents a yes/no question * Enforces strict responses rather than non-standard answers counting as default * Based on Symfony\Component\Console\Question\ConfirmationQuestion * * @author Theo Tonge <theo@theotonge.co.uk> */ class StrictConfirmationQuestion extends Question { /** @var non-empty-string */ private $trueAnswerRegex; /** @var non-empty-string */ private $falseAnswerRegex; /** * Constructor.s * * @param string $question The question to ask to the user * @param bool $default The default answer to return, true or false * @param non-empty-string $trueAnswerRegex A regex to match the "yes" answer * @param non-empty-string $falseAnswerRegex A regex to match the "no" answer */ public function __construct(string $question, bool $default = true, string $trueAnswerRegex = '/^y(?:es)?$/i', string $falseAnswerRegex = '/^no?$/i') { parent::__construct($question, $default); $this->trueAnswerRegex = $trueAnswerRegex; $this->falseAnswerRegex = $falseAnswerRegex; $this->setNormalizer($this->getDefaultNormalizer()); $this->setValidator($this->getDefaultValidator()); } /** * Returns the default answer normalizer. */ private function getDefaultNormalizer(): callable { $default = $this->getDefault(); $trueRegex = $this->trueAnswerRegex; $falseRegex = $this->falseAnswerRegex; return static function ($answer) use ($default, $trueRegex, $falseRegex) { if (is_bool($answer)) { return $answer; } if (empty($answer) && !empty($default)) { return $default; } if (Preg::isMatch($trueRegex, $answer)) { return true; } if (Preg::isMatch($falseRegex, $answer)) { return false; } return null; }; } /** * Returns the default answer validator. */ private function getDefaultValidator(): callable { return static function ($answer): bool { if (!is_bool($answer)) { throw new InvalidArgumentException('Please answer yes, y, no, or n.'); } return $answer; }; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Autoload/AutoloadGenerator.php
src/Composer/Autoload/AutoloadGenerator.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\Autoload; use Composer\ClassMapGenerator\ClassMap; use Composer\ClassMapGenerator\ClassMapGenerator; use Composer\Config; use Composer\EventDispatcher\EventDispatcher; use Composer\Filter\PlatformRequirementFilter\IgnoreAllPlatformRequirementFilter; use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterFactory; use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterInterface; use Composer\Installer\InstallationManager; use Composer\IO\IOInterface; use Composer\IO\NullIO; use Composer\Package\AliasPackage; use Composer\Package\PackageInterface; use Composer\Package\RootPackageInterface; use Composer\Pcre\Preg; use Composer\Repository\InstalledRepositoryInterface; use Composer\Semver\Constraint\Bound; use Composer\Util\Filesystem; use Composer\Util\Platform; use Composer\Script\ScriptEvents; use Composer\Util\PackageSorter; use Composer\Json\JsonFile; use Composer\Package\Locker; use Symfony\Component\Console\Formatter\OutputFormatter; /** * @author Igor Wiedler <igor@wiedler.ch> * @author Jordi Boggiano <j.boggiano@seld.be> */ class AutoloadGenerator { /** * @var EventDispatcher */ private $eventDispatcher; /** * @var IOInterface */ private $io; /** * @var ?bool */ private $devMode = null; /** * @var bool */ private $classMapAuthoritative = false; /** * @var bool */ private $apcu = false; /** * @var string|null */ private $apcuPrefix; /** * @var bool */ private $dryRun = false; /** * @var bool */ private $runScripts = false; /** * @var PlatformRequirementFilterInterface */ private $platformRequirementFilter; public function __construct(EventDispatcher $eventDispatcher, ?IOInterface $io = null) { $this->eventDispatcher = $eventDispatcher; $this->io = $io ?? new NullIO(); $this->platformRequirementFilter = PlatformRequirementFilterFactory::ignoreNothing(); } /** * @return void */ public function setDevMode(bool $devMode = true) { $this->devMode = $devMode; } /** * Whether generated autoloader considers the class map authoritative. * * @return void */ public function setClassMapAuthoritative(bool $classMapAuthoritative) { $this->classMapAuthoritative = $classMapAuthoritative; } /** * Whether generated autoloader considers APCu caching. * * @return void */ public function setApcu(bool $apcu, ?string $apcuPrefix = null) { $this->apcu = $apcu; $this->apcuPrefix = $apcuPrefix; } /** * Whether to run scripts or not * * @return void */ public function setRunScripts(bool $runScripts = true) { $this->runScripts = $runScripts; } /** * Whether to run in drymode or not */ public function setDryRun(bool $dryRun = true): void { $this->dryRun = $dryRun; } /** * Whether platform requirements should be ignored. * * If this is set to true, the platform check file will not be generated * If this is set to false, the platform check file will be generated with all requirements * If this is set to string[], those packages will be ignored from the platform check file * * @param bool|string[] $ignorePlatformReqs * @return void * * @deprecated use setPlatformRequirementFilter instead */ public function setIgnorePlatformRequirements($ignorePlatformReqs) { trigger_error('AutoloadGenerator::setIgnorePlatformRequirements is deprecated since Composer 2.2, use setPlatformRequirementFilter instead.', E_USER_DEPRECATED); $this->setPlatformRequirementFilter(PlatformRequirementFilterFactory::fromBoolOrList($ignorePlatformReqs)); } /** * @return void */ public function setPlatformRequirementFilter(PlatformRequirementFilterInterface $platformRequirementFilter) { $this->platformRequirementFilter = $platformRequirementFilter; } /** * @return ClassMap * @throws \Seld\JsonLint\ParsingException * @throws \RuntimeException */ public function dump(Config $config, InstalledRepositoryInterface $localRepo, RootPackageInterface $rootPackage, InstallationManager $installationManager, string $targetDir, bool $scanPsrPackages = false, ?string $suffix = null, ?Locker $locker = null, bool $strictAmbiguous = false) { if ($this->classMapAuthoritative) { // Force scanPsrPackages when classmap is authoritative $scanPsrPackages = true; } // auto-set devMode based on whether dev dependencies are installed or not if (null === $this->devMode) { // we assume no-dev mode if no vendor dir is present or it is too old to contain dev information $this->devMode = false; $installedJson = new JsonFile($config->get('vendor-dir').'/composer/installed.json'); if ($installedJson->exists()) { $installedJson = $installedJson->read(); if (isset($installedJson['dev'])) { $this->devMode = $installedJson['dev']; } } } if ($this->runScripts) { // set COMPOSER_DEV_MODE in case not set yet so it is available in the dump-autoload event listeners if (!isset($_SERVER['COMPOSER_DEV_MODE'])) { Platform::putEnv('COMPOSER_DEV_MODE', $this->devMode ? '1' : '0'); } $this->eventDispatcher->dispatchScript(ScriptEvents::PRE_AUTOLOAD_DUMP, $this->devMode, [], [ 'optimize' => $scanPsrPackages, ]); } $classMapGenerator = new ClassMapGenerator(['php', 'inc', 'hh']); $classMapGenerator->avoidDuplicateScans(); $filesystem = new Filesystem(); $filesystem->ensureDirectoryExists($config->get('vendor-dir')); // Do not remove double realpath() calls. // Fixes failing Windows realpath() implementation. // See https://bugs.php.net/bug.php?id=72738 $basePath = $filesystem->normalizePath(realpath(realpath(Platform::getCwd()))); $vendorPath = $filesystem->normalizePath(realpath(realpath($config->get('vendor-dir')))); $useGlobalIncludePath = $config->get('use-include-path'); $prependAutoloader = $config->get('prepend-autoloader') === false ? 'false' : 'true'; $targetDir = $vendorPath.'/'.$targetDir; $filesystem->ensureDirectoryExists($targetDir); $vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true); $vendorPathToTargetDirCode = $filesystem->findShortestPathCode($vendorPath, realpath($targetDir), true); $appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, $basePath, true); $appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode); $namespacesFile = <<<EOF <?php // autoload_namespaces.php @generated by Composer \$vendorDir = $vendorPathCode; \$baseDir = $appBaseDirCode; return array( EOF; $psr4File = <<<EOF <?php // autoload_psr4.php @generated by Composer \$vendorDir = $vendorPathCode; \$baseDir = $appBaseDirCode; return array( EOF; // Collect information from all packages. $devPackageNames = $localRepo->getDevPackageNames(); $packageMap = $this->buildPackageMap($installationManager, $rootPackage, $localRepo->getCanonicalPackages()); if ($this->devMode) { // if dev mode is enabled, then we do not filter any dev packages out so disable this entirely $filteredDevPackages = false; } else { // if the list of dev package names is available we use that straight, otherwise pass true which means use legacy algo to figure them out $filteredDevPackages = $devPackageNames ?: true; } $autoloads = $this->parseAutoloads($packageMap, $rootPackage, $filteredDevPackages); // Process the 'psr-0' base directories. foreach ($autoloads['psr-0'] as $namespace => $paths) { $exportedPaths = []; foreach ($paths as $path) { $exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path); } $exportedPrefix = var_export($namespace, true); $namespacesFile .= " $exportedPrefix => "; $namespacesFile .= "array(".implode(', ', $exportedPaths)."),\n"; } $namespacesFile .= ");\n"; // Process the 'psr-4' base directories. foreach ($autoloads['psr-4'] as $namespace => $paths) { $exportedPaths = []; foreach ($paths as $path) { $exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path); } $exportedPrefix = var_export($namespace, true); $psr4File .= " $exportedPrefix => "; $psr4File .= "array(".implode(', ', $exportedPaths)."),\n"; } $psr4File .= ");\n"; // add custom psr-0 autoloading if the root package has a target dir $targetDirLoader = null; $mainAutoload = $rootPackage->getAutoload(); if ($rootPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) { $levels = substr_count($filesystem->normalizePath($rootPackage->getTargetDir()), '/') + 1; $prefixes = implode(', ', array_map(static function ($prefix): string { return var_export($prefix, true); }, array_keys($mainAutoload['psr-0']))); $baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, $basePath, true); $targetDirLoader = <<<EOF public static function autoload(\$class) { \$dir = $baseDirFromTargetDirCode . '/'; \$prefixes = array($prefixes); foreach (\$prefixes as \$prefix) { if (0 !== strpos(\$class, \$prefix)) { continue; } \$path = \$dir . implode('/', array_slice(explode('\\\\', \$class), $levels)).'.php'; if (!\$path = stream_resolve_include_path(\$path)) { return false; } require \$path; return true; } } EOF; } $excluded = []; if (!empty($autoloads['exclude-from-classmap'])) { $excluded = $autoloads['exclude-from-classmap']; } foreach ($autoloads['classmap'] as $dir) { $classMapGenerator->scanPaths($dir, $this->buildExclusionRegex($dir, $excluded)); } if ($scanPsrPackages) { $namespacesToScan = []; // Scan the PSR-0/4 directories for class files, and add them to the class map foreach (['psr-4', 'psr-0'] as $psrType) { foreach ($autoloads[$psrType] as $namespace => $paths) { $namespacesToScan[$namespace][] = ['paths' => $paths, 'type' => $psrType]; } } krsort($namespacesToScan); foreach ($namespacesToScan as $namespace => $groups) { foreach ($groups as $group) { foreach ($group['paths'] as $dir) { $dir = $filesystem->normalizePath($filesystem->isAbsolutePath($dir) ? $dir : $basePath.'/'.$dir); if (!is_dir($dir)) { continue; } // if the vendor dir is contained within a psr-0/psr-4 dir being scanned we exclude it if (str_contains($vendorPath, $dir.'/')) { $exclusionRegex = $this->buildExclusionRegex($dir, array_merge($excluded, [$vendorPath.'/'])); } else { $exclusionRegex = $this->buildExclusionRegex($dir, $excluded); } $classMapGenerator->scanPaths($dir, $exclusionRegex, $group['type'], $namespace); } } } } $classMap = $classMapGenerator->getClassMap(); if ($strictAmbiguous) { $ambiguousClasses = $classMap->getAmbiguousClasses(false); } else { $ambiguousClasses = $classMap->getAmbiguousClasses(); } foreach ($ambiguousClasses as $className => $ambiguousPaths) { if (count($ambiguousPaths) > 1) { $this->io->writeError( '<warning>Warning: Ambiguous class resolution, "'.$className.'"'. ' was found '. (count($ambiguousPaths) + 1) .'x: in "'.$classMap->getClassPath($className).'" and "'. implode('", "', $ambiguousPaths) .'", the first will be used.</warning>' ); } else { $this->io->writeError( '<warning>Warning: Ambiguous class resolution, "'.$className.'"'. ' was found in both "'.$classMap->getClassPath($className).'" and "'. implode('", "', $ambiguousPaths) .'", the first will be used.</warning>' ); } } if (\count($ambiguousClasses) > 0) { $this->io->writeError('<info>To resolve ambiguity in classes not under your control you can ignore them by path using <href='.OutputFormatter::escape('https://getcomposer.org/doc/04-schema.md#exclude-files-from-classmaps').'>exclude-from-classmap</>'); } // output PSR violations which are not coming from the vendor dir $classMap->clearPsrViolationsByPath($vendorPath); foreach ($classMap->getPsrViolations() as $msg) { $this->io->writeError("<warning>$msg</warning>"); } $classMap->addClass('Composer\InstalledVersions', $vendorPath . '/composer/InstalledVersions.php'); $classMap->sort(); $classmapFile = <<<EOF <?php // autoload_classmap.php @generated by Composer \$vendorDir = $vendorPathCode; \$baseDir = $appBaseDirCode; return array( EOF; foreach ($classMap->getMap() as $className => $path) { $pathCode = $this->getPathCode($filesystem, $basePath, $vendorPath, $path).",\n"; $classmapFile .= ' '.var_export($className, true).' => '.$pathCode; } $classmapFile .= ");\n"; if ('' === $suffix) { $suffix = null; } if (null === $suffix) { $suffix = $config->get('autoloader-suffix'); // carry over existing autoload.php's suffix if possible and none is configured if (null === $suffix && Filesystem::isReadable($vendorPath.'/autoload.php')) { $content = (string) file_get_contents($vendorPath.'/autoload.php'); if (Preg::isMatch('{ComposerAutoloaderInit([^:\s]+)::}', $content, $match)) { $suffix = $match[1]; } } if (null === $suffix) { $suffix = $locker !== null && $locker->isLocked() ? $locker->getLockData()['content-hash'] : bin2hex(random_bytes(16)); } } if ($this->dryRun) { return $classMap; } $filesystem->filePutContentsIfModified($targetDir.'/autoload_namespaces.php', $namespacesFile); $filesystem->filePutContentsIfModified($targetDir.'/autoload_psr4.php', $psr4File); $filesystem->filePutContentsIfModified($targetDir.'/autoload_classmap.php', $classmapFile); $includePathFilePath = $targetDir.'/include_paths.php'; if ($includePathFileContents = $this->getIncludePathsFile($packageMap, $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode)) { $filesystem->filePutContentsIfModified($includePathFilePath, $includePathFileContents); } elseif (file_exists($includePathFilePath)) { unlink($includePathFilePath); } $includeFilesFilePath = $targetDir.'/autoload_files.php'; if ($includeFilesFileContents = $this->getIncludeFilesFile($autoloads['files'], $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode)) { $filesystem->filePutContentsIfModified($includeFilesFilePath, $includeFilesFileContents); } elseif (file_exists($includeFilesFilePath)) { unlink($includeFilesFilePath); } $filesystem->filePutContentsIfModified($targetDir.'/autoload_static.php', $this->getStaticFile($suffix, $targetDir, $vendorPath, $basePath)); $checkPlatform = $config->get('platform-check') !== false && !($this->platformRequirementFilter instanceof IgnoreAllPlatformRequirementFilter); $platformCheckContent = null; if ($checkPlatform) { $platformCheckContent = $this->getPlatformCheck($packageMap, $config->get('platform-check'), $devPackageNames); if (null === $platformCheckContent) { $checkPlatform = false; } } if ($checkPlatform) { $filesystem->filePutContentsIfModified($targetDir.'/platform_check.php', $platformCheckContent); } elseif (file_exists($targetDir.'/platform_check.php')) { unlink($targetDir.'/platform_check.php'); } $filesystem->filePutContentsIfModified($vendorPath.'/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, $suffix)); $filesystem->filePutContentsIfModified($targetDir.'/autoload_real.php', $this->getAutoloadRealFile(true, (bool) $includePathFileContents, $targetDirLoader, (bool) $includeFilesFileContents, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader, $checkPlatform)); $filesystem->safeCopy(__DIR__.'/ClassLoader.php', $targetDir.'/ClassLoader.php'); $filesystem->safeCopy(__DIR__.'/../../../LICENSE', $targetDir.'/LICENSE'); if ($this->runScripts) { $this->eventDispatcher->dispatchScript(ScriptEvents::POST_AUTOLOAD_DUMP, $this->devMode, [], [ 'optimize' => $scanPsrPackages, ]); } return $classMap; } /** * @param array<string> $excluded * @return non-empty-string|null */ private function buildExclusionRegex(string $dir, array $excluded): ?string { if ([] === $excluded) { return null; } // filter excluded patterns here to only use those matching $dir // exclude-from-classmap patterns are all realpath'd so we can only filter them if $dir exists so that realpath($dir) will work // if $dir does not exist, it should anyway not find anything there so no trouble if (file_exists($dir)) { // transform $dir in the same way that exclude-from-classmap patterns are transformed so we can match them against each other $dirMatch = preg_quote(strtr(realpath($dir), '\\', '/')); // also match against the non-realpath version for symlinks $fs = new Filesystem(); $absDir = $fs->isAbsolutePath($dir) ? $dir : realpath(Platform::getCwd()).'/'.$dir; $dirMatchNormalized = preg_quote(strtr($fs->normalizePath($absDir), '\\', '/')); $isSymlink = $dirMatch !== $dirMatchNormalized; foreach ($excluded as $index => $pattern) { // extract the constant string prefix of the pattern here, until we reach a non-escaped regex special character $pattern = Preg::replace('{^(([^.+*?\[^\]$(){}=!<>|:\\\\#-]+|\\\\[.+*?\[^\]$(){}=!<>|:#-])*).*}', '$1', $pattern); // if the pattern is not a subset or superset of $dir, it is unrelated and we skip it if ( (!str_starts_with($pattern, $dirMatch) && !str_starts_with($dirMatch, $pattern)) && ( // only check dirMatchNormalized if it is actually different from dirMatch otherwise there is no point !$isSymlink || (!str_starts_with($pattern, $dirMatchNormalized) && !str_starts_with($dirMatchNormalized, $pattern)) ) ) { unset($excluded[$index]); } } } return \count($excluded) > 0 ? '{(' . implode('|', $excluded) . ')}' : null; } /** * @param PackageInterface[] $packages * @return non-empty-array<int, array{0: PackageInterface, 1: string|null}> */ public function buildPackageMap(InstallationManager $installationManager, PackageInterface $rootPackage, array $packages) { // build package => install path map $packageMap = [[$rootPackage, '']]; foreach ($packages as $package) { if ($package instanceof AliasPackage) { continue; } $this->validatePackage($package); $packageMap[] = [ $package, $installationManager->getInstallPath($package), ]; } return $packageMap; } /** * @return void * @throws \InvalidArgumentException Throws an exception, if the package has illegal settings. */ protected function validatePackage(PackageInterface $package) { $autoload = $package->getAutoload(); if (!empty($autoload['psr-4']) && null !== $package->getTargetDir()) { $name = $package->getName(); $package->getTargetDir(); throw new \InvalidArgumentException("PSR-4 autoloading is incompatible with the target-dir property, remove the target-dir in package '$name'."); } if (!empty($autoload['psr-4'])) { foreach ($autoload['psr-4'] as $namespace => $dirs) { if ($namespace !== '' && '\\' !== substr($namespace, -1)) { throw new \InvalidArgumentException("psr-4 namespaces must end with a namespace separator, '$namespace' does not, use '$namespace\\'."); } } } } /** * Compiles an ordered list of namespace => path mappings * * @param non-empty-array<int, array{0: PackageInterface, 1: string|null}> $packageMap array of array(package, installDir-relative-to-composer.json or null for metapackages) * @param RootPackageInterface $rootPackage root package instance * @param bool|string[] $filteredDevPackages If an array, the list of packages that must be removed. If bool, whether to filter out require-dev packages * @return array * @phpstan-return array{ * 'psr-0': array<string, array<string>>, * 'psr-4': array<string, array<string>>, * 'classmap': array<int, string>, * 'files': array<string, string>, * 'exclude-from-classmap': array<int, string>, * } */ public function parseAutoloads(array $packageMap, PackageInterface $rootPackage, $filteredDevPackages = false) { $rootPackageMap = array_shift($packageMap); if (is_array($filteredDevPackages)) { $packageMap = array_filter($packageMap, static function ($item) use ($filteredDevPackages): bool { return !in_array($item[0]->getName(), $filteredDevPackages, true); }); } elseif ($filteredDevPackages) { $packageMap = $this->filterPackageMap($packageMap, $rootPackage); } $sortedPackageMap = $this->sortPackageMap($packageMap); $sortedPackageMap[] = $rootPackageMap; $reverseSortedMap = array_reverse($sortedPackageMap); // reverse-sorted means root first, then dependents, then their dependents, etc. // which makes sense to allow root to override classmap or psr-0/4 entries with higher precedence rules $psr0 = $this->parseAutoloadsType($reverseSortedMap, 'psr-0', $rootPackage); $psr4 = $this->parseAutoloadsType($reverseSortedMap, 'psr-4', $rootPackage); $classmap = $this->parseAutoloadsType($reverseSortedMap, 'classmap', $rootPackage); // sorted (i.e. dependents first) for files to ensure that dependencies are loaded/available once a file is included $files = $this->parseAutoloadsType($sortedPackageMap, 'files', $rootPackage); // using sorted here but it does not really matter as all are excluded equally $exclude = $this->parseAutoloadsType($sortedPackageMap, 'exclude-from-classmap', $rootPackage); krsort($psr0); krsort($psr4); return [ 'psr-0' => $psr0, 'psr-4' => $psr4, 'classmap' => $classmap, 'files' => $files, 'exclude-from-classmap' => $exclude, ]; } /** * Registers an autoloader based on an autoload-map returned by parseAutoloads * * @param array<string, mixed[]> $autoloads see parseAutoloads return value * @return ClassLoader */ public function createLoader(array $autoloads, ?string $vendorDir = null) { $loader = new ClassLoader($vendorDir); if (isset($autoloads['psr-0'])) { foreach ($autoloads['psr-0'] as $namespace => $path) { $loader->add($namespace, $path); } } if (isset($autoloads['psr-4'])) { foreach ($autoloads['psr-4'] as $namespace => $path) { $loader->addPsr4($namespace, $path); } } if (isset($autoloads['classmap'])) { $excluded = []; if (!empty($autoloads['exclude-from-classmap'])) { $excluded = $autoloads['exclude-from-classmap']; } $classMapGenerator = new ClassMapGenerator(['php', 'inc', 'hh']); $classMapGenerator->avoidDuplicateScans(); foreach ($autoloads['classmap'] as $dir) { try { $classMapGenerator->scanPaths($dir, $this->buildExclusionRegex($dir, $excluded)); } catch (\RuntimeException $e) { $this->io->writeError('<warning>'.$e->getMessage().'</warning>'); } } $loader->addClassMap($classMapGenerator->getClassMap()->getMap()); } return $loader; } /** * @param array<int, array{0: PackageInterface, 1: string|null}> $packageMap * @return ?string */ protected function getIncludePathsFile(array $packageMap, Filesystem $filesystem, string $basePath, string $vendorPath, string $vendorPathCode, string $appBaseDirCode) { $includePaths = []; foreach ($packageMap as $item) { [$package, $installPath] = $item; // packages that are not installed cannot autoload anything if (null === $installPath) { continue; } if (null !== $package->getTargetDir() && strlen($package->getTargetDir()) > 0) { $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir())); } foreach ($package->getIncludePaths() as $includePath) { $includePath = trim($includePath, '/'); $includePaths[] = $installPath === '' ? $includePath : $installPath.'/'.$includePath; } } if (\count($includePaths) === 0) { return null; } $includePathsCode = ''; foreach ($includePaths as $path) { $includePathsCode .= " " . $this->getPathCode($filesystem, $basePath, $vendorPath, $path) . ",\n"; } return <<<EOF <?php // include_paths.php @generated by Composer \$vendorDir = $vendorPathCode; \$baseDir = $appBaseDirCode; return array( $includePathsCode); EOF; } /** * @param array<string, string> $files * @return ?string */ protected function getIncludeFilesFile(array $files, Filesystem $filesystem, string $basePath, string $vendorPath, string $vendorPathCode, string $appBaseDirCode) { // Get the path to each file, and make sure these paths are unique. $files = array_map( function (string $functionFile) use ($filesystem, $basePath, $vendorPath): string { return $this->getPathCode($filesystem, $basePath, $vendorPath, $functionFile); }, $files ); $uniqueFiles = array_unique($files); if (count($uniqueFiles) < count($files)) { $this->io->writeError('<warning>The following "files" autoload rules are included multiple times, this may cause issues and should be resolved:</warning>'); foreach (array_unique(array_diff_assoc($files, $uniqueFiles)) as $duplicateFile) { $this->io->writeError('<warning> - '.$duplicateFile.'</warning>'); } } unset($uniqueFiles); $filesCode = ''; foreach ($files as $fileIdentifier => $functionFile) { $filesCode .= ' ' . var_export($fileIdentifier, true) . ' => ' . $functionFile . ",\n"; } if (!$filesCode) { return null; } return <<<EOF <?php // autoload_files.php @generated by Composer \$vendorDir = $vendorPathCode; \$baseDir = $appBaseDirCode; return array( $filesCode); EOF; } /** * @return string */ protected function getPathCode(Filesystem $filesystem, string $basePath, string $vendorPath, string $path) { if (!$filesystem->isAbsolutePath($path)) { $path = $basePath . '/' . $path; } $path = $filesystem->normalizePath($path); $baseDir = ''; if (strpos($path.'/', $vendorPath.'/') === 0) { $path = (string) substr($path, strlen($vendorPath)); $baseDir = '$vendorDir . '; } else { $path = $filesystem->normalizePath($filesystem->findShortestPath($basePath, $path, true)); if (!$filesystem->isAbsolutePath($path)) { $baseDir = '$baseDir . '; $path = '/' . $path; } } if (Preg::isMatch('{\.phar([\\\\/]|$)}', $path)) { $baseDir = "'phar://' . " . $baseDir; } return $baseDir . var_export($path, true); } /** * @param array<int, array{0: PackageInterface, 1: string|null}> $packageMap * @param bool|'php-only' $checkPlatform * @param string[] $devPackageNames * @return ?string */ protected function getPlatformCheck(array $packageMap, $checkPlatform, array $devPackageNames) { $lowestPhpVersion = Bound::zero(); $requiredPhp64bit = false; $requiredExtensions = []; $extensionProviders = []; foreach ($packageMap as $item) { $package = $item[0]; foreach (array_merge($package->getReplaces(), $package->getProvides()) as $link) { if (Preg::isMatch('{^ext-(.+)$}iD', $link->getTarget(), $match)) { $extensionProviders[$match[1]][] = $link->getConstraint(); } } } foreach ($packageMap as $item) { $package = $item[0]; // skip dev dependencies platform requirements as platform-check really should only be a production safeguard if (in_array($package->getName(), $devPackageNames, true)) { continue; } foreach ($package->getRequires() as $link) { if ($this->platformRequirementFilter->isIgnored($link->getTarget())) { continue; } if (in_array($link->getTarget(), ['php', 'php-64bit'], true)) { $constraint = $link->getConstraint(); if ($constraint->getLowerBound()->compareTo($lowestPhpVersion, '>')) { $lowestPhpVersion = $constraint->getLowerBound(); } } if ('php-64bit' === $link->getTarget()) { $requiredPhp64bit = true; } if ($checkPlatform === true && Preg::isMatch('{^ext-(.+)$}iD', $link->getTarget(), $match)) { // skip extension checks if they have a valid provider/replacer if (isset($extensionProviders[$match[1]])) { foreach ($extensionProviders[$match[1]] as $provided) {
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
true
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Autoload/ClassMapGenerator.php
src/Composer/Autoload/ClassMapGenerator.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. */ /* * This file is copied from the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> */ namespace Composer\Autoload; use Composer\ClassMapGenerator\FileList; use Composer\IO\IOInterface; /** * ClassMapGenerator * * @author Gyula Sallai <salla016@gmail.com> * @author Jordi Boggiano <j.boggiano@seld.be> * * @deprecated Since Composer 2.4.0 use the composer/class-map-generator package instead */ class ClassMapGenerator { /** * Generate a class map file * * @param \Traversable<string>|array<string> $dirs Directories or a single path to search in * @param string $file The name of the class map file */ public static function dump(iterable $dirs, string $file): void { $maps = []; foreach ($dirs as $dir) { $maps = array_merge($maps, static::createMap($dir)); } file_put_contents($file, sprintf('<?php return %s;', var_export($maps, true))); } /** * Iterate over all files in the given directory searching for classes * * @param \Traversable<\SplFileInfo>|string|array<\SplFileInfo> $path The path to search in or an iterator * @param non-empty-string|null $excluded Regex that matches file paths to be excluded from the classmap * @param ?IOInterface $io IO object * @param null|string $namespace Optional namespace prefix to filter by * @param null|'psr-0'|'psr-4'|'classmap' $autoloadType psr-0|psr-4 Optional autoload standard to use mapping rules * @param array<non-empty-string, true> $scannedFiles * @return array<class-string, non-empty-string> A class map array * @throws \RuntimeException When the path is neither an existing file nor directory */ public static function createMap($path, ?string $excluded = null, ?IOInterface $io = null, ?string $namespace = null, ?string $autoloadType = null, array &$scannedFiles = []): array { $generator = new \Composer\ClassMapGenerator\ClassMapGenerator(['php', 'inc', 'hh']); $fileList = new FileList(); $fileList->files = $scannedFiles; $generator->avoidDuplicateScans($fileList); $generator->scanPaths($path, $excluded, $autoloadType ?? 'classmap', $namespace); $classMap = $generator->getClassMap(); $scannedFiles = $fileList->files; if ($io !== null) { foreach ($classMap->getPsrViolations() as $msg) { $io->writeError("<warning>$msg</warning>"); } foreach ($classMap->getAmbiguousClasses() as $class => $paths) { if (count($paths) > 1) { $io->writeError( '<warning>Warning: Ambiguous class resolution, "'.$class.'"'. ' was found '. (count($paths) + 1) .'x: in "'.$classMap->getClassPath($class).'" and "'. implode('", "', $paths) .'", the first will be used.</warning>' ); } else { $io->writeError( '<warning>Warning: Ambiguous class resolution, "'.$class.'"'. ' was found in both "'.$classMap->getClassPath($class).'" and "'. implode('", "', $paths) .'", the first will be used.</warning>' ); } } } return $classMap->getMap(); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Autoload/ClassLoader.php
src/Composer/Autoload/ClassLoader.php
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Autoload; /** * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. * * $loader = new \Composer\Autoload\ClassLoader(); * * // register classes with namespaces * $loader->add('Symfony\Component', __DIR__.'/component'); * $loader->add('Symfony', __DIR__.'/framework'); * * // activate the autoloader * $loader->register(); * * // to enable searching the include path (eg. for PEAR packages) * $loader->setUseIncludePath(true); * * In this example, if you try to use a class in the Symfony\Component * namespace or one of its children (Symfony\Component\Console for instance), * the autoloader will first look for the class under the component/ * directory, and it will then fallback to the framework/ directory if not * found before giving up. * * This class is loosely based on the Symfony UniversalClassLoader. * * @author Fabien Potencier <fabien@symfony.com> * @author Jordi Boggiano <j.boggiano@seld.be> * @see https://www.php-fig.org/psr/psr-0/ * @see https://www.php-fig.org/psr/psr-4/ */ class ClassLoader { /** @var \Closure(string):void */ private static $includeFile; /** @var string|null */ private $vendorDir; // PSR-4 /** * @var array<string, array<string, int>> */ private $prefixLengthsPsr4 = array(); /** * @var array<string, list<string>> */ private $prefixDirsPsr4 = array(); /** * @var list<string> */ private $fallbackDirsPsr4 = array(); // PSR-0 /** * List of PSR-0 prefixes * * Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2'))) * * @var array<string, array<string, list<string>>> */ private $prefixesPsr0 = array(); /** * @var list<string> */ private $fallbackDirsPsr0 = array(); /** @var bool */ private $useIncludePath = false; /** * @var array<string, string> */ private $classMap = array(); /** @var bool */ private $classMapAuthoritative = false; /** * @var array<string, bool> */ private $missingClasses = array(); /** @var string|null */ private $apcuPrefix; /** * @var array<string, self> */ private static $registeredLoaders = array(); /** * @param string|null $vendorDir */ public function __construct($vendorDir = null) { $this->vendorDir = $vendorDir; self::initializeIncludeClosure(); } /** * @return array<string, list<string>> */ public function getPrefixes() { if (!empty($this->prefixesPsr0)) { return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); } return array(); } /** * @return array<string, list<string>> */ public function getPrefixesPsr4() { return $this->prefixDirsPsr4; } /** * @return list<string> */ public function getFallbackDirs() { return $this->fallbackDirsPsr0; } /** * @return list<string> */ public function getFallbackDirsPsr4() { return $this->fallbackDirsPsr4; } /** * @return array<string, string> Array of classname => path */ public function getClassMap() { return $this->classMap; } /** * @param array<string, string> $classMap Class to filename map * * @return void */ public function addClassMap(array $classMap) { if ($this->classMap) { $this->classMap = array_merge($this->classMap, $classMap); } else { $this->classMap = $classMap; } } /** * Registers a set of PSR-0 directories for a given prefix, either * appending or prepending to the ones previously set for this prefix. * * @param string $prefix The prefix * @param list<string>|string $paths The PSR-0 root directories * @param bool $prepend Whether to prepend the directories * * @return void */ public function add($prefix, $paths, $prepend = false) { $paths = (array) $paths; if (!$prefix) { if ($prepend) { $this->fallbackDirsPsr0 = array_merge( $paths, $this->fallbackDirsPsr0 ); } else { $this->fallbackDirsPsr0 = array_merge( $this->fallbackDirsPsr0, $paths ); } return; } $first = $prefix[0]; if (!isset($this->prefixesPsr0[$first][$prefix])) { $this->prefixesPsr0[$first][$prefix] = $paths; return; } if ($prepend) { $this->prefixesPsr0[$first][$prefix] = array_merge( $paths, $this->prefixesPsr0[$first][$prefix] ); } else { $this->prefixesPsr0[$first][$prefix] = array_merge( $this->prefixesPsr0[$first][$prefix], $paths ); } } /** * Registers a set of PSR-4 directories for a given namespace, either * appending or prepending to the ones previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' * @param list<string>|string $paths The PSR-4 base directories * @param bool $prepend Whether to prepend the directories * * @throws \InvalidArgumentException * * @return void */ public function addPsr4($prefix, $paths, $prepend = false) { $paths = (array) $paths; if (!$prefix) { // Register directories for the root namespace. if ($prepend) { $this->fallbackDirsPsr4 = array_merge( $paths, $this->fallbackDirsPsr4 ); } else { $this->fallbackDirsPsr4 = array_merge( $this->fallbackDirsPsr4, $paths ); } } elseif (!isset($this->prefixDirsPsr4[$prefix])) { // Register directories for a new namespace. $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = $paths; } elseif ($prepend) { // Prepend directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( $paths, $this->prefixDirsPsr4[$prefix] ); } else { // Append directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( $this->prefixDirsPsr4[$prefix], $paths ); } } /** * Registers a set of PSR-0 directories for a given prefix, * replacing any others previously set for this prefix. * * @param string $prefix The prefix * @param list<string>|string $paths The PSR-0 base directories * * @return void */ public function set($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr0 = (array) $paths; } else { $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; } } /** * Registers a set of PSR-4 directories for a given namespace, * replacing any others previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' * @param list<string>|string $paths The PSR-4 base directories * * @throws \InvalidArgumentException * * @return void */ public function setPsr4($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr4 = (array) $paths; } else { $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } } /** * Turns on searching the include path for class files. * * @param bool $useIncludePath * * @return void */ public function setUseIncludePath($useIncludePath) { $this->useIncludePath = $useIncludePath; } /** * Can be used to check if the autoloader uses the include path to check * for classes. * * @return bool */ public function getUseIncludePath() { return $this->useIncludePath; } /** * Turns off searching the prefix and fallback directories for classes * that have not been registered with the class map. * * @param bool $classMapAuthoritative * * @return void */ public function setClassMapAuthoritative($classMapAuthoritative) { $this->classMapAuthoritative = $classMapAuthoritative; } /** * Should class lookup fail if not found in the current class map? * * @return bool */ public function isClassMapAuthoritative() { return $this->classMapAuthoritative; } /** * APCu prefix to use to cache found/not-found classes, if the extension is enabled. * * @param string|null $apcuPrefix * * @return void */ public function setApcuPrefix($apcuPrefix) { $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; } /** * The APCu prefix in use, or null if APCu caching is not enabled. * * @return string|null */ public function getApcuPrefix() { return $this->apcuPrefix; } /** * Registers this instance as an autoloader. * * @param bool $prepend Whether to prepend the autoloader or not * * @return void */ public function register($prepend = false) { spl_autoload_register(array($this, 'loadClass'), true, $prepend); if (null === $this->vendorDir) { return; } if ($prepend) { self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; } else { unset(self::$registeredLoaders[$this->vendorDir]); self::$registeredLoaders[$this->vendorDir] = $this; } } /** * Unregisters this instance as an autoloader. * * @return void */ public function unregister() { spl_autoload_unregister(array($this, 'loadClass')); if (null !== $this->vendorDir) { unset(self::$registeredLoaders[$this->vendorDir]); } } /** * Loads the given class or interface. * * @param string $class The name of the class * @return true|null True if loaded, null otherwise */ public function loadClass($class) { if ($file = $this->findFile($class)) { $includeFile = self::$includeFile; $includeFile($file); return true; } return null; } /** * Finds the path to the file where the class is defined. * * @param string $class The name of the class * * @return string|false The path if found, false otherwise */ public function findFile($class) { // class map lookup if (isset($this->classMap[$class])) { return $this->classMap[$class]; } if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { return false; } if (null !== $this->apcuPrefix) { $file = apcu_fetch($this->apcuPrefix.$class, $hit); if ($hit) { return $file; } } $file = $this->findFileWithExtension($class, '.php'); // Search for Hack files if we are running on HHVM if (false === $file && defined('HHVM_VERSION')) { $file = $this->findFileWithExtension($class, '.hh'); } if (null !== $this->apcuPrefix) { apcu_add($this->apcuPrefix.$class, $file); } if (false === $file) { // Remember that this class does not exist. $this->missingClasses[$class] = true; } return $file; } /** * Returns the currently registered loaders keyed by their corresponding vendor directories. * * @return array<string, self> */ public static function getRegisteredLoaders() { return self::$registeredLoaders; } /** * @param string $class * @param string $ext * @return string|false */ private function findFileWithExtension($class, $ext) { // PSR-4 lookup $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; $first = $class[0]; if (isset($this->prefixLengthsPsr4[$first])) { $subPath = $class; while (false !== $lastPos = strrpos($subPath, '\\')) { $subPath = substr($subPath, 0, $lastPos); $search = $subPath . '\\'; if (isset($this->prefixDirsPsr4[$search])) { $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); foreach ($this->prefixDirsPsr4[$search] as $dir) { if (file_exists($file = $dir . $pathEnd)) { return $file; } } } } } // PSR-4 fallback dirs foreach ($this->fallbackDirsPsr4 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { return $file; } } // PSR-0 lookup if (false !== $pos = strrpos($class, '\\')) { // namespaced class name $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); } else { // PEAR-like class name $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; } if (isset($this->prefixesPsr0[$first])) { foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { if (0 === strpos($class, $prefix)) { foreach ($dirs as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } } } } // PSR-0 fallback dirs foreach ($this->fallbackDirsPsr0 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } // PSR-0 include paths. if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { return $file; } return false; } /** * @return void */ private static function initializeIncludeClosure() { if (self::$includeFile !== null) { return; } /** * Scope isolated include. * * Prevents access to $this/self from included files. * * @param string $file * @return void */ self::$includeFile = \Closure::bind(static function($file) { include $file; }, null, null); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Script/ScriptEvents.php
src/Composer/Script/ScriptEvents.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\Script; /** * The Script Events. * * @author François Pluchino <francois.pluchino@opendisplay.com> * @author Jordi Boggiano <j.boggiano@seld.be> */ class ScriptEvents { /** * The PRE_INSTALL_CMD event occurs before the install command is executed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ public const PRE_INSTALL_CMD = 'pre-install-cmd'; /** * The POST_INSTALL_CMD event occurs after the install command is executed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ public const POST_INSTALL_CMD = 'post-install-cmd'; /** * The PRE_UPDATE_CMD event occurs before the update command is executed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ public const PRE_UPDATE_CMD = 'pre-update-cmd'; /** * The POST_UPDATE_CMD event occurs after the update command is executed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ public const POST_UPDATE_CMD = 'post-update-cmd'; /** * The PRE_STATUS_CMD event occurs before the status command is executed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ public const PRE_STATUS_CMD = 'pre-status-cmd'; /** * The POST_STATUS_CMD event occurs after the status command is executed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ public const POST_STATUS_CMD = 'post-status-cmd'; /** * The PRE_AUTOLOAD_DUMP event occurs before the autoload file is generated. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ public const PRE_AUTOLOAD_DUMP = 'pre-autoload-dump'; /** * The POST_AUTOLOAD_DUMP event occurs after the autoload file has been generated. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ public const POST_AUTOLOAD_DUMP = 'post-autoload-dump'; /** * The POST_ROOT_PACKAGE_INSTALL event occurs after the root package has been installed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ public const POST_ROOT_PACKAGE_INSTALL = 'post-root-package-install'; /** * The POST_CREATE_PROJECT event occurs after the create-project command has been executed. * Note: Event occurs after POST_INSTALL_CMD * * The event listener method receives a Composer\Script\Event instance. * * @var string */ public const POST_CREATE_PROJECT_CMD = 'post-create-project-cmd'; /** * The PRE_ARCHIVE_CMD event occurs before the update command is executed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ public const PRE_ARCHIVE_CMD = 'pre-archive-cmd'; /** * The POST_ARCHIVE_CMD event occurs after the status command is executed. * * The event listener method receives a Composer\Script\Event instance. * * @var string */ public const POST_ARCHIVE_CMD = 'post-archive-cmd'; }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Script/Event.php
src/Composer/Script/Event.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\Script; use Composer\Composer; use Composer\IO\IOInterface; use Composer\EventDispatcher\Event as BaseEvent; /** * The script event class * * @author François Pluchino <francois.pluchino@opendisplay.com> * @author Nils Adermann <naderman@naderman.de> */ class Event extends BaseEvent { /** * @var Composer The composer instance */ private $composer; /** * @var IOInterface The IO instance */ private $io; /** * @var bool Dev mode flag */ private $devMode; /** * @var BaseEvent|null */ private $originatingEvent; /** * Constructor. * * @param string $name The event name * @param Composer $composer The composer object * @param IOInterface $io The IOInterface object * @param bool $devMode Whether or not we are in dev mode * @param array<string|int|float|bool|null> $args Arguments passed by the user * @param mixed[] $flags Optional flags to pass data not as argument */ public function __construct(string $name, Composer $composer, IOInterface $io, bool $devMode = false, array $args = [], array $flags = []) { parent::__construct($name, $args, $flags); $this->composer = $composer; $this->io = $io; $this->devMode = $devMode; } /** * Returns the composer instance. */ public function getComposer(): Composer { return $this->composer; } /** * Returns the IO instance. */ public function getIO(): IOInterface { return $this->io; } /** * Return the dev mode flag */ public function isDevMode(): bool { return $this->devMode; } /** * Set the originating event. */ public function getOriginatingEvent(): ?BaseEvent { return $this->originatingEvent; } /** * Set the originating event. * * @return $this */ public function setOriginatingEvent(BaseEvent $event): self { $this->originatingEvent = $this->calculateOriginatingEvent($event); return $this; } /** * Returns the upper-most event in chain. */ private function calculateOriginatingEvent(BaseEvent $event): BaseEvent { if ($event instanceof Event && $event->getOriginatingEvent()) { return $this->calculateOriginatingEvent($event->getOriginatingEvent()); } return $event; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Plugin/PostFileDownloadEvent.php
src/Composer/Plugin/PostFileDownloadEvent.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\Plugin; use Composer\EventDispatcher\Event; use Composer\Package\PackageInterface; /** * The post file download event. * * @author Nils Adermann <naderman@naderman.de> */ class PostFileDownloadEvent extends Event { /** * @var string */ private $fileName; /** * @var string|null */ private $checksum; /** * @var string */ private $url; /** * @var mixed */ private $context; /** * @var string */ private $type; /** * Constructor. * * @param string $name The event name * @param string|null $fileName The file name * @param string|null $checksum The checksum * @param string $url The processed url * @param string $type The type (package or metadata). * @param mixed $context Additional context for the download. */ public function __construct(string $name, ?string $fileName, ?string $checksum, string $url, string $type, $context = null) { /** @phpstan-ignore instanceof.alwaysFalse, booleanAnd.alwaysFalse */ if ($context === null && $type instanceof PackageInterface) { $context = $type; $type = 'package'; trigger_error('PostFileDownloadEvent::__construct should receive a $type=package and the package object in $context since Composer 2.1.', E_USER_DEPRECATED); } parent::__construct($name); $this->fileName = $fileName; $this->checksum = $checksum; $this->url = $url; $this->context = $context; $this->type = $type; } /** * Retrieves the target file name location. * * If this download is of type metadata, null is returned. */ public function getFileName(): ?string { return $this->fileName; } /** * Gets the checksum. */ public function getChecksum(): ?string { return $this->checksum; } /** * Gets the processed URL. */ public function getUrl(): string { return $this->url; } /** * Returns the context of this download, if any. * * If this download is of type package, the package object is returned. If * this download is of type metadata, an array{response: Response, repository: RepositoryInterface} is returned. * * @return mixed */ public function getContext() { return $this->context; } /** * Get the package. * * If this download is of type metadata, null is returned. * * @return PackageInterface|null The package. * @deprecated Use getContext instead */ public function getPackage(): ?PackageInterface { trigger_error('PostFileDownloadEvent::getPackage is deprecated since Composer 2.1, use getContext instead.', E_USER_DEPRECATED); $context = $this->getContext(); return $context instanceof PackageInterface ? $context : null; } /** * Returns the type of this download (package, metadata). */ public function getType(): string { return $this->type; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Plugin/PluginInterface.php
src/Composer/Plugin/PluginInterface.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\Plugin; use Composer\Composer; use Composer\IO\IOInterface; /** * Plugin interface * * @author Nils Adermann <naderman@naderman.de> */ interface PluginInterface { /** * Version number of the internal composer-plugin-api package * * This is used to denote the API version of Plugin specific * features, but is also bumped to a new major if Composer * includes a major break in internal APIs which are susceptible * to be used by plugins. * * @var string */ public const PLUGIN_API_VERSION = '2.9.0'; /** * Apply plugin modifications to Composer * * @return void */ public function activate(Composer $composer, IOInterface $io); /** * Remove any hooks from Composer * * This will be called when a plugin is deactivated before being * uninstalled, but also before it gets upgraded to a new version * so the old one can be deactivated and the new one activated. * * @return void */ public function deactivate(Composer $composer, IOInterface $io); /** * Prepare the plugin to be uninstalled * * This will be called after deactivate. * * @return void */ public function uninstall(Composer $composer, IOInterface $io); }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Plugin/PluginManager.php
src/Composer/Plugin/PluginManager.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\Plugin; use Composer\Composer; use Composer\EventDispatcher\EventSubscriberInterface; use Composer\Installer\InstallerInterface; use Composer\IO\IOInterface; use Composer\Package\BasePackage; use Composer\Package\CompletePackage; use Composer\Package\Locker; use Composer\Package\Package; use Composer\Package\RootPackageInterface; use Composer\Package\Version\VersionParser; use Composer\PartialComposer; use Composer\Pcre\Preg; use Composer\Repository\RepositoryInterface; use Composer\Repository\InstalledRepository; use Composer\Repository\RepositoryUtils; use Composer\Repository\RootPackageRepository; use Composer\Package\PackageInterface; use Composer\Package\Link; use Composer\Semver\Constraint\Constraint; use Composer\Plugin\Capability\Capability; use Composer\Util\PackageSorter; /** * Plugin manager * * @author Nils Adermann <naderman@naderman.de> * @author Jordi Boggiano <j.boggiano@seld.be> */ class PluginManager { /** @var Composer */ protected $composer; /** @var IOInterface */ protected $io; /** @var PartialComposer|null */ protected $globalComposer; /** @var VersionParser */ protected $versionParser; /** @var bool|'local'|'global' */ protected $disablePlugins = false; /** @var array<PluginInterface> */ protected $plugins = []; /** @var array<string, array<PluginInterface|InstallerInterface>> */ protected $registeredPlugins = []; /** * @var array<non-empty-string, bool>|null */ private $allowPluginRules; /** * @var array<non-empty-string, bool>|null */ private $allowGlobalPluginRules; /** @var bool */ private $runningInGlobalDir = false; /** @var int */ private static $classCounter = 0; /** * @param bool|'local'|'global' $disablePlugins Whether plugins should not be loaded, can be set to local or global to only disable local/global plugins */ public function __construct(IOInterface $io, Composer $composer, ?PartialComposer $globalComposer = null, $disablePlugins = false) { $this->io = $io; $this->composer = $composer; $this->globalComposer = $globalComposer; $this->versionParser = new VersionParser(); $this->disablePlugins = $disablePlugins; $this->allowPluginRules = $this->parseAllowedPlugins($composer->getConfig()->get('allow-plugins'), $composer->getLocker()); $this->allowGlobalPluginRules = $this->parseAllowedPlugins($globalComposer !== null ? $globalComposer->getConfig()->get('allow-plugins') : false); } public function setRunningInGlobalDir(bool $runningInGlobalDir): void { $this->runningInGlobalDir = $runningInGlobalDir; } /** * Loads all plugins from currently installed plugin packages */ public function loadInstalledPlugins(): void { if (!$this->arePluginsDisabled('local')) { $repo = $this->composer->getRepositoryManager()->getLocalRepository(); $this->loadRepository($repo, false, $this->composer->getPackage()); } if ($this->globalComposer !== null && !$this->arePluginsDisabled('global')) { $this->loadRepository($this->globalComposer->getRepositoryManager()->getLocalRepository(), true); } } /** * Deactivate all plugins from currently installed plugin packages */ public function deactivateInstalledPlugins(): void { if (!$this->arePluginsDisabled('local')) { $repo = $this->composer->getRepositoryManager()->getLocalRepository(); $this->deactivateRepository($repo, false); } if ($this->globalComposer !== null && !$this->arePluginsDisabled('global')) { $this->deactivateRepository($this->globalComposer->getRepositoryManager()->getLocalRepository(), true); } } /** * Gets all currently active plugin instances * * @return array<PluginInterface> plugins */ public function getPlugins(): array { return $this->plugins; } /** * Gets all currently active plugin instances * * @internal * @return array<string> Plugin package names which are currently active */ public function getRegisteredPlugins(): array { return array_keys($this->registeredPlugins); } /** * Gets global composer or null when main composer is not fully loaded */ public function getGlobalComposer(): ?PartialComposer { return $this->globalComposer; } /** * Register a plugin package, activate it etc. * * If it's of type composer-installer it is registered as an installer * instead for BC * * @param bool $failOnMissingClasses By default this silently skips plugins that can not be found, but if set to true it fails with an exception * @param bool $isGlobalPlugin Set to true to denote plugins which are installed in the global Composer directory * * @throws \UnexpectedValueException */ public function registerPackage(PackageInterface $package, bool $failOnMissingClasses = false, bool $isGlobalPlugin = false): void { if ($this->arePluginsDisabled($isGlobalPlugin ? 'global' : 'local')) { $this->io->writeError('<warning>The "'.$package->getName().'" plugin was not loaded as plugins are disabled.</warning>'); return; } if ($package->getType() === 'composer-plugin') { $requiresComposer = null; foreach ($package->getRequires() as $link) { /** @var Link $link */ if ('composer-plugin-api' === $link->getTarget()) { $requiresComposer = $link->getConstraint(); break; } } if (!$requiresComposer) { throw new \RuntimeException("Plugin ".$package->getName()." is missing a require statement for a version of the composer-plugin-api package."); } $currentPluginApiVersion = $this->getPluginApiVersion(); $currentPluginApiConstraint = new Constraint('==', $this->versionParser->normalize($currentPluginApiVersion)); if ($requiresComposer->getPrettyString() === $this->getPluginApiVersion()) { $this->io->writeError('<warning>The "' . $package->getName() . '" plugin requires composer-plugin-api '.$this->getPluginApiVersion().', this *WILL* break in the future and it should be fixed ASAP (require ^'.$this->getPluginApiVersion().' instead for example).</warning>'); } elseif (!$requiresComposer->matches($currentPluginApiConstraint)) { $this->io->writeError('<warning>The "' . $package->getName() . '" plugin '.($isGlobalPlugin || $this->runningInGlobalDir ? '(installed globally) ' : '').'was skipped because it requires a Plugin API version ("' . $requiresComposer->getPrettyString() . '") that does not match your Composer installation ("' . $currentPluginApiVersion . '"). You may need to run composer update with the "--no-plugins" option.</warning>'); return; } if ($package->getName() === 'symfony/flex' && Preg::isMatch('{^[0-9.]+$}', $package->getVersion()) && version_compare($package->getVersion(), '1.9.8', '<')) { $this->io->writeError('<warning>The "' . $package->getName() . '" plugin '.($isGlobalPlugin || $this->runningInGlobalDir ? '(installed globally) ' : '').'was skipped because it is not compatible with Composer 2+. Make sure to update it to version 1.9.8 or greater.</warning>'); return; } } if (!$this->isPluginAllowed($package->getName(), $isGlobalPlugin, true === ($package->getExtra()['plugin-optional'] ?? false))) { $this->io->writeError('Skipped loading "'.$package->getName() . '" '.($isGlobalPlugin || $this->runningInGlobalDir ? '(installed globally) ' : '').'as it is not in config.allow-plugins', true, IOInterface::DEBUG); return; } $oldInstallerPlugin = ($package->getType() === 'composer-installer'); if (isset($this->registeredPlugins[$package->getName()])) { return; } $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.'); } $classes = is_array($extra['class']) ? $extra['class'] : [$extra['class']]; $localRepo = $this->composer->getRepositoryManager()->getLocalRepository(); $globalRepo = $this->globalComposer !== null ? $this->globalComposer->getRepositoryManager()->getLocalRepository() : null; $rootPackage = clone $this->composer->getPackage(); // clear files autoload rules from the root package as the root dependencies are not // necessarily all present yet when booting this runtime autoloader $rootPackageAutoloads = $rootPackage->getAutoload(); $rootPackageAutoloads['files'] = []; $rootPackage->setAutoload($rootPackageAutoloads); $rootPackageAutoloads = $rootPackage->getDevAutoload(); $rootPackageAutoloads['files'] = []; $rootPackage->setDevAutoload($rootPackageAutoloads); unset($rootPackageAutoloads); $rootPackageRepo = new RootPackageRepository($rootPackage); $installedRepo = new InstalledRepository([$localRepo, $rootPackageRepo]); if ($globalRepo) { $installedRepo->addRepository($globalRepo); } $autoloadPackages = [$package->getName() => $package]; $autoloadPackages = $this->collectDependencies($installedRepo, $autoloadPackages, $package); $generator = $this->composer->getAutoloadGenerator(); $autoloads = [[$rootPackage, '']]; foreach ($autoloadPackages as $autoloadPackage) { if ($autoloadPackage === $rootPackage) { continue; } $installPath = $this->getInstallPath($autoloadPackage, $globalRepo && $globalRepo->hasPackage($autoloadPackage)); if ($installPath === null) { continue; } $autoloads[] = [$autoloadPackage, $installPath]; } $map = $generator->parseAutoloads($autoloads, $rootPackage); $classLoader = $generator->createLoader($map, $this->composer->getConfig()->get('vendor-dir')); $classLoader->register(false); foreach ($map['files'] as $fileIdentifier => $file) { // exclude laminas/laminas-zendframework-bridge:src/autoload.php as it breaks Composer in some conditions // see https://github.com/composer/composer/issues/10349 and https://github.com/composer/composer/issues/10401 // this hack can be removed once this deprecated package stop being installed if ($fileIdentifier === '7e9bd612cc444b3eed788ebbe46263a0') { continue; } \Composer\Autoload\composerRequire($fileIdentifier, $file); } foreach ($classes as $class) { if (class_exists($class, false)) { $class = trim($class, '\\'); $path = $classLoader->findFile($class); $code = file_get_contents($path); $separatorPos = strrpos($class, '\\'); $className = $class; if ($separatorPos) { $className = substr($class, $separatorPos + 1); } $code = Preg::replace('{^((?:(?:final|readonly)\s+)*(?:\s*))class\s+('.preg_quote($className).')}mi', '$1class $2_composer_tmp'.self::$classCounter, $code, 1); $code = strtr($code, [ '__FILE__' => var_export($path, true), '__DIR__' => var_export(dirname($path), true), '__CLASS__' => var_export($class, true), ]); $code = Preg::replace('/^\s*<\?(php)?/i', '', $code, 1); eval($code); $class .= '_composer_tmp'.self::$classCounter; self::$classCounter++; } if ($oldInstallerPlugin) { if (!is_a($class, 'Composer\Installer\InstallerInterface', true)) { throw new \RuntimeException('Could not activate plugin "'.$package->getName().'" as "'.$class.'" does not implement Composer\Installer\InstallerInterface'); } $this->io->writeError('<warning>Loading "'.$package->getName() . '" '.($isGlobalPlugin || $this->runningInGlobalDir ? '(installed globally) ' : '').'which is a legacy composer-installer built for Composer 1.x, it is likely to cause issues as you are running Composer 2.x.</warning>'); $installer = new $class($this->io, $this->composer); $this->composer->getInstallationManager()->addInstaller($installer); $this->registeredPlugins[$package->getName()][] = $installer; } elseif (class_exists($class)) { if (!is_a($class, 'Composer\Plugin\PluginInterface', true)) { throw new \RuntimeException('Could not activate plugin "'.$package->getName().'" as "'.$class.'" does not implement Composer\Plugin\PluginInterface'); } $plugin = new $class(); $this->addPlugin($plugin, $isGlobalPlugin, $package); $this->registeredPlugins[$package->getName()][] = $plugin; } elseif ($failOnMissingClasses) { throw new \UnexpectedValueException('Plugin '.$package->getName().' could not be initialized, class not found: '.$class); } } } /** * Deactivates a plugin package * * If it's of type composer-installer it is unregistered from the installers * instead for BC * * @throws \UnexpectedValueException */ public function deactivatePackage(PackageInterface $package): void { if (!isset($this->registeredPlugins[$package->getName()])) { return; } $plugins = $this->registeredPlugins[$package->getName()]; foreach ($plugins as $plugin) { if ($plugin instanceof InstallerInterface) { $this->composer->getInstallationManager()->removeInstaller($plugin); } else { $this->removePlugin($plugin); } } unset($this->registeredPlugins[$package->getName()]); } /** * Uninstall a plugin package * * If it's of type composer-installer it is unregistered from the installers * instead for BC * * @throws \UnexpectedValueException */ public function uninstallPackage(PackageInterface $package): void { if (!isset($this->registeredPlugins[$package->getName()])) { return; } $plugins = $this->registeredPlugins[$package->getName()]; foreach ($plugins as $plugin) { if ($plugin instanceof InstallerInterface) { $this->composer->getInstallationManager()->removeInstaller($plugin); } else { $this->removePlugin($plugin); $this->uninstallPlugin($plugin); } } unset($this->registeredPlugins[$package->getName()]); } /** * Returns the version of the internal composer-plugin-api package. */ protected function getPluginApiVersion(): string { return PluginInterface::PLUGIN_API_VERSION; } /** * Adds a plugin, activates it and registers it with the event dispatcher * * Ideally plugin packages should be registered via registerPackage, but if you use Composer * programmatically and want to register a plugin class directly this is a valid way * to do it. * * @param PluginInterface $plugin plugin instance * @param ?PackageInterface $sourcePackage Package from which the plugin comes from */ public function addPlugin(PluginInterface $plugin, bool $isGlobalPlugin = false, ?PackageInterface $sourcePackage = null): void { if ($this->arePluginsDisabled($isGlobalPlugin ? 'global' : 'local')) { return; } if ($sourcePackage === null) { trigger_error('Calling PluginManager::addPlugin without $sourcePackage is deprecated, if you are using this please get in touch with us to explain the use case', E_USER_DEPRECATED); } elseif (!$this->isPluginAllowed($sourcePackage->getName(), $isGlobalPlugin, true === ($sourcePackage->getExtra()['plugin-optional'] ?? false))) { $this->io->writeError('Skipped loading "'.get_class($plugin).' from '.$sourcePackage->getName() . '" '.($isGlobalPlugin || $this->runningInGlobalDir ? '(installed globally) ' : '').' as it is not in config.allow-plugins', true, IOInterface::DEBUG); return; } $details = []; if ($sourcePackage) { $details[] = 'from '.$sourcePackage->getName(); } if ($isGlobalPlugin || $this->runningInGlobalDir) { $details[] = 'installed globally'; } $this->io->writeError('Loading plugin '.get_class($plugin).($details ? ' ('.implode(', ', $details).')' : ''), true, IOInterface::DEBUG); $this->plugins[] = $plugin; $plugin->activate($this->composer, $this->io); if ($plugin instanceof EventSubscriberInterface) { $this->composer->getEventDispatcher()->addSubscriber($plugin); } } /** * Removes a plugin, deactivates it and removes any listener the plugin has set on the plugin instance * * Ideally plugin packages should be deactivated via deactivatePackage, but if you use Composer * programmatically and want to deregister a plugin class directly this is a valid way * to do it. * * @param PluginInterface $plugin plugin instance */ public function removePlugin(PluginInterface $plugin): void { $index = array_search($plugin, $this->plugins, true); if ($index === false) { return; } $this->io->writeError('Unloading plugin '.get_class($plugin), true, IOInterface::DEBUG); unset($this->plugins[$index]); $plugin->deactivate($this->composer, $this->io); $this->composer->getEventDispatcher()->removeListener($plugin); } /** * Notifies a plugin it is being uninstalled and should clean up * * Ideally plugin packages should be uninstalled via uninstallPackage, but if you use Composer * programmatically and want to deregister a plugin class directly this is a valid way * to do it. * * @param PluginInterface $plugin plugin instance */ public function uninstallPlugin(PluginInterface $plugin): void { $this->io->writeError('Uninstalling plugin '.get_class($plugin), true, IOInterface::DEBUG); $plugin->uninstall($this->composer, $this->io); } /** * Load all plugins and installers from a repository * * If a plugin requires another plugin, the required one will be loaded first * * Note that plugins in the specified repository that rely on events that * have fired prior to loading will be missed. This means you likely want to * call this method as early as possible. * * @param RepositoryInterface $repo Repository to scan for plugins to install * * @phpstan-param ($isGlobalRepo is true ? null : RootPackageInterface) $rootPackage * * @throws \RuntimeException */ private function loadRepository(RepositoryInterface $repo, bool $isGlobalRepo, ?RootPackageInterface $rootPackage = null): void { $packages = $repo->getPackages(); $weights = []; foreach ($packages as $package) { if ($package->getType() === 'composer-plugin') { $extra = $package->getExtra(); if ($package->getName() === 'composer/installers' || true === ($extra['plugin-modifies-install-path'] ?? false)) { $weights[$package->getName()] = -10000; } } } $sortedPackages = PackageSorter::sortPackages($packages, $weights); if (!$isGlobalRepo) { $requiredPackages = RepositoryUtils::filterRequiredPackages($packages, $rootPackage, true); } foreach ($sortedPackages as $package) { if (!($package instanceof CompletePackage)) { continue; } if (!in_array($package->getType(), ['composer-plugin', 'composer-installer'], true)) { continue; } if ( !$isGlobalRepo && !in_array($package, $requiredPackages, true) && !$this->isPluginAllowed($package->getName(), false, true, false) ) { $this->io->writeError('<warning>The "'.$package->getName().'" plugin was not loaded as it is not listed in allow-plugins and is not required by the root package anymore.</warning>'); continue; } if ('composer-plugin' === $package->getType()) { $this->registerPackage($package, false, $isGlobalRepo); // Backward compatibility } elseif ('composer-installer' === $package->getType()) { $this->registerPackage($package, false, $isGlobalRepo); } } } /** * Deactivate all plugins and installers from a repository * * If a plugin requires another plugin, the required one will be deactivated last * * @param RepositoryInterface $repo Repository to scan for plugins to install */ private function deactivateRepository(RepositoryInterface $repo, bool $isGlobalRepo): void { $packages = $repo->getPackages(); $sortedPackages = array_reverse(PackageSorter::sortPackages($packages)); foreach ($sortedPackages as $package) { if (!($package instanceof CompletePackage)) { continue; } if ('composer-plugin' === $package->getType()) { $this->deactivatePackage($package); // Backward compatibility } elseif ('composer-installer' === $package->getType()) { $this->deactivatePackage($package); } } } /** * Recursively generates a map of package names to packages for all deps * * @param InstalledRepository $installedRepo Set of local repos * @param array<string, PackageInterface> $collected Current state of the map for recursion * @param PackageInterface $package The package to analyze * * @return array<string, PackageInterface> Map of package names to packages */ private function collectDependencies(InstalledRepository $installedRepo, array $collected, PackageInterface $package): array { foreach ($package->getRequires() as $requireLink) { foreach ($installedRepo->findPackagesWithReplacersAndProviders($requireLink->getTarget()) as $requiredPackage) { if (!isset($collected[$requiredPackage->getName()])) { $collected[$requiredPackage->getName()] = $requiredPackage; $collected = $this->collectDependencies($installedRepo, $collected, $requiredPackage); } } } return $collected; } /** * Retrieves the path a package is installed to. * * @param bool $global Whether this is a global package * * @return string|null Install path */ private function getInstallPath(PackageInterface $package, bool $global = false): ?string { if (!$global) { return $this->composer->getInstallationManager()->getInstallPath($package); } assert(null !== $this->globalComposer); return $this->globalComposer->getInstallationManager()->getInstallPath($package); } /** * @throws \RuntimeException On empty or non-string implementation class name value * @return null|string The fully qualified class of the implementation or null if Plugin is not of Capable type or does not provide it */ protected function getCapabilityImplementationClassName(PluginInterface $plugin, string $capability): ?string { if (!($plugin instanceof Capable)) { return null; } $capabilities = (array) $plugin->getCapabilities(); if (!empty($capabilities[$capability]) && is_string($capabilities[$capability]) && trim($capabilities[$capability])) { return trim($capabilities[$capability]); } if ( array_key_exists($capability, $capabilities) && (empty($capabilities[$capability]) || !is_string($capabilities[$capability]) || !trim($capabilities[$capability])) ) { throw new \UnexpectedValueException('Plugin '.get_class($plugin).' provided invalid capability class name(s), got '.var_export($capabilities[$capability], true)); } return null; } /** * @template CapabilityClass of Capability * @param class-string<CapabilityClass> $capabilityClassName The fully qualified name of the API interface which the plugin may provide * an implementation of. * @param array<mixed> $ctorArgs Arguments passed to Capability's constructor. * Keeping it an array will allow future values to be passed w\o changing the signature. * @phpstan-param class-string<CapabilityClass> $capabilityClassName * @phpstan-return null|CapabilityClass */ public function getPluginCapability(PluginInterface $plugin, $capabilityClassName, array $ctorArgs = []): ?Capability { if ($capabilityClass = $this->getCapabilityImplementationClassName($plugin, $capabilityClassName)) { if (!class_exists($capabilityClass)) { throw new \RuntimeException("Cannot instantiate Capability, as class $capabilityClass from plugin ".get_class($plugin)." does not exist."); } $ctorArgs['plugin'] = $plugin; $capabilityObj = new $capabilityClass($ctorArgs); // FIXME these could use is_a and do the check *before* instantiating once drop support for php<5.3.9 if (!$capabilityObj instanceof Capability || !$capabilityObj instanceof $capabilityClassName) { throw new \RuntimeException( 'Class ' . $capabilityClass . ' must implement both Composer\Plugin\Capability\Capability and '. $capabilityClassName . '.' ); } return $capabilityObj; } return null; } /** * @template CapabilityClass of Capability * @param class-string<CapabilityClass> $capabilityClassName The fully qualified name of the API interface which the plugin may provide * an implementation of. * @param array<mixed> $ctorArgs Arguments passed to Capability's constructor. * Keeping it an array will allow future values to be passed w\o changing the signature. * @return CapabilityClass[] */ public function getPluginCapabilities($capabilityClassName, array $ctorArgs = []): array { $capabilities = []; foreach ($this->getPlugins() as $plugin) { $capability = $this->getPluginCapability($plugin, $capabilityClassName, $ctorArgs); if (null !== $capability) { $capabilities[] = $capability; } } return $capabilities; } /** * @param array<string, bool>|bool $allowPluginsConfig * @return array<non-empty-string, bool>|null */ private function parseAllowedPlugins($allowPluginsConfig, ?Locker $locker = null): ?array { if ([] === $allowPluginsConfig && $locker !== null && $locker->isLocked() && version_compare($locker->getPluginApi(), '2.2.0', '<')) { return null; } if (true === $allowPluginsConfig) { return ['{}' => true]; } if (false === $allowPluginsConfig) { return ['{}' => false]; } $rules = []; foreach ($allowPluginsConfig as $pattern => $allow) { $rules[BasePackage::packageNameToRegexp($pattern)] = $allow; } return $rules; } /** * @internal * * @param 'local'|'global' $type * @return bool */ public function arePluginsDisabled($type) { return $this->disablePlugins === true || $this->disablePlugins === $type; } /** * @internal */ public function disablePlugins(): void { $this->disablePlugins = true; } /** * @internal */ public function isPluginAllowed(string $package, bool $isGlobalPlugin, bool $optional = false, bool $prompt = true): bool { if ($isGlobalPlugin) { $rules = &$this->allowGlobalPluginRules; } else { $rules = &$this->allowPluginRules; } // This is a BC mode for lock files created pre-Composer-2.2 where the expectation of // an allow-plugins config being present cannot be made. if ($rules === null) { if (!$this->io->isInteractive()) { $this->io->writeError('<warning>For additional security you should declare the allow-plugins config with a list of packages names that are allowed to run code. See https://getcomposer.org/allow-plugins</warning>'); $this->io->writeError('<warning>This warning will become an exception once you run composer update!</warning>'); $rules = ['{}' => true]; // if no config is defined we allow all plugins for BC return true; } // keep going and prompt the user $rules = []; } foreach ($rules as $pattern => $allow) { if (Preg::isMatch($pattern, $package)) { return $allow === true; } } if ($package === 'composer/package-versions-deprecated') { return false; } if ($this->io->isInteractive() && $prompt) { $composer = $isGlobalPlugin && $this->globalComposer !== null ? $this->globalComposer : $this->composer; $this->io->writeError('<warning>'.$package.($isGlobalPlugin || $this->runningInGlobalDir ? ' (installed globally)' : '').' contains a Composer plugin which is currently not in your allow-plugins config. See https://getcomposer.org/allow-plugins</warning>'); $attempts = 0; while (true) { // do not allow more than 5 prints of the help message, at some point assume the // input is not interactive and bail defaulting to a disabled plugin $default = '?'; if ($attempts > 5) { $this->io->writeError('Too many failed prompts, aborting.'); break; } switch ($answer = $this->io->ask('Do you trust "<fg=green;options=bold>'.$package.'</>" to execute code and wish to enable it now? (writes "allow-plugins" to composer.json) [<comment>y,n,d,?</comment>] ', $default)) { case 'y': case 'n': case 'd': $allow = $answer === 'y'; // persist answer in current rules to avoid prompting again if the package gets reloaded $rules[BasePackage::packageNameToRegexp($package)] = $allow; // persist answer in composer.json if it wasn't simply discarded if ($answer === 'y' || $answer === 'n') { $allowPlugins = $composer->getConfig()->get('allow-plugins');
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
true
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Plugin/PluginEvents.php
src/Composer/Plugin/PluginEvents.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\Plugin; /** * The Plugin Events. * * @author Nils Adermann <naderman@naderman.de> */ class PluginEvents { /** * The INIT event occurs after a Composer instance is done being initialized * * The event listener method receives a * Composer\EventDispatcher\Event instance. * * @var string */ public const INIT = 'init'; /** * The COMMAND event occurs as a command begins * * The event listener method receives a * Composer\Plugin\CommandEvent instance. * * @var string */ public const COMMAND = 'command'; /** * The PRE_FILE_DOWNLOAD event occurs before downloading a file * * The event listener method receives a * Composer\Plugin\PreFileDownloadEvent instance. * * @var string */ public const PRE_FILE_DOWNLOAD = 'pre-file-download'; /** * The POST_FILE_DOWNLOAD event occurs after downloading a package dist file * * The event listener method receives a * Composer\Plugin\PostFileDownloadEvent instance. * * @var string */ public const POST_FILE_DOWNLOAD = 'post-file-download'; /** * The PRE_COMMAND_RUN event occurs before a command is executed and lets you modify the input arguments/options * * The event listener method receives a * Composer\Plugin\PreCommandRunEvent instance. * * @var string */ public const PRE_COMMAND_RUN = 'pre-command-run'; /** * The PRE_POOL_CREATE event occurs before the Pool of packages is created, and lets * you filter the list of packages which is going to enter the Solver * * The event listener method receives a * Composer\Plugin\PrePoolCreateEvent instance. * * @var string */ public const PRE_POOL_CREATE = 'pre-pool-create'; }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Plugin/Capable.php
src/Composer/Plugin/Capable.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\Plugin; /** * Plugins which need to expose various implementations * of the Composer Plugin Capabilities must have their * declared Plugin class implementing this interface. * * @api */ interface Capable { /** * Method by which a Plugin announces its API implementations, through an array * with a special structure. * * The key must be a string, representing a fully qualified class/interface name * which Composer Plugin API exposes. * The value must be a string as well, representing the fully qualified class name * of the implementing class. * * @tutorial * * return array( * 'Composer\Plugin\Capability\CommandProvider' => 'My\CommandProvider', * 'Composer\Plugin\Capability\Validator' => 'My\Validator', * ); * * @return string[] */ public function getCapabilities(); }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Plugin/PluginBlockedException.php
src/Composer/Plugin/PluginBlockedException.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\Plugin; use UnexpectedValueException; class PluginBlockedException extends UnexpectedValueException { }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Plugin/PreCommandRunEvent.php
src/Composer/Plugin/PreCommandRunEvent.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\Plugin; use Composer\EventDispatcher\Event; use Symfony\Component\Console\Input\InputInterface; /** * The pre command run event. * * @author Jordi Boggiano <j.boggiano@seld.be> */ class PreCommandRunEvent extends Event { /** * @var InputInterface */ private $input; /** * @var string */ private $command; /** * Constructor. * * @param string $name The event name * @param string $command The command about to be executed */ public function __construct(string $name, InputInterface $input, string $command) { parent::__construct($name); $this->input = $input; $this->command = $command; } /** * Returns the console input */ public function getInput(): InputInterface { return $this->input; } /** * Returns the command about to be executed */ public function getCommand(): string { return $this->command; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Plugin/PreFileDownloadEvent.php
src/Composer/Plugin/PreFileDownloadEvent.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\Plugin; use Composer\EventDispatcher\Event; use Composer\Util\HttpDownloader; /** * The pre file download event. * * @author Nils Adermann <naderman@naderman.de> */ class PreFileDownloadEvent extends Event { /** * @var HttpDownloader */ private $httpDownloader; /** * @var non-empty-string */ private $processedUrl; /** * @var string|null */ private $customCacheKey; /** * @var string */ private $type; /** * @var mixed */ private $context; /** * @var mixed[] */ private $transportOptions = []; /** * Constructor. * * @param string $name The event name * @param mixed $context * @param non-empty-string $processedUrl */ public function __construct(string $name, HttpDownloader $httpDownloader, string $processedUrl, string $type, $context = null) { parent::__construct($name); $this->httpDownloader = $httpDownloader; $this->processedUrl = $processedUrl; $this->type = $type; $this->context = $context; } public function getHttpDownloader(): HttpDownloader { return $this->httpDownloader; } /** * Retrieves the processed URL that will be downloaded. * * @return non-empty-string */ public function getProcessedUrl(): string { return $this->processedUrl; } /** * Sets the processed URL that will be downloaded. * * @param non-empty-string $processedUrl New processed URL */ public function setProcessedUrl(string $processedUrl): void { $this->processedUrl = $processedUrl; } /** * Retrieves a custom package cache key for this download. */ public function getCustomCacheKey(): ?string { return $this->customCacheKey; } /** * Sets a custom package cache key for this download. * * @param string|null $customCacheKey New cache key */ public function setCustomCacheKey(?string $customCacheKey): void { $this->customCacheKey = $customCacheKey; } /** * Returns the type of this download (package, metadata). */ public function getType(): string { return $this->type; } /** * Returns the context of this download, if any. * * If this download is of type package, the package object is returned. * If the type is metadata, an array{repository: RepositoryInterface} is returned. * * @return mixed */ public function getContext() { return $this->context; } /** * Returns transport options for the download. * * Only available for events with type metadata, for packages set the transport options on the package itself. * * @return mixed[] */ public function getTransportOptions(): array { return $this->transportOptions; } /** * Sets transport options for the download. * * Only available for events with type metadata, for packages set the transport options on the package itself. * * @param mixed[] $options */ public function setTransportOptions(array $options): void { $this->transportOptions = $options; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Plugin/PrePoolCreateEvent.php
src/Composer/Plugin/PrePoolCreateEvent.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\Plugin; use Composer\EventDispatcher\Event; use Composer\Repository\RepositoryInterface; use Composer\DependencyResolver\Request; use Composer\Package\BasePackage; /** * The pre command run event. * * @author Jordi Boggiano <j.boggiano@seld.be> */ class PrePoolCreateEvent extends Event { /** * @var RepositoryInterface[] */ private $repositories; /** * @var Request */ private $request; /** * @var int[] array of stability => BasePackage::STABILITY_* value * @phpstan-var array<string, BasePackage::STABILITY_*> */ private $acceptableStabilities; /** * @var int[] array of package name => BasePackage::STABILITY_* value * @phpstan-var array<string, BasePackage::STABILITY_*> */ private $stabilityFlags; /** * @var array[] of package => version => [alias, alias_normalized] * @phpstan-var array<string, array<string, array{alias: string, alias_normalized: string}>> */ private $rootAliases; /** * @var string[] * @phpstan-var array<string, string> */ private $rootReferences; /** * @var BasePackage[] */ private $packages; /** * @var BasePackage[] */ private $unacceptableFixedPackages; /** * @param string $name The event name * @param RepositoryInterface[] $repositories * @param int[] $acceptableStabilities array of stability => BasePackage::STABILITY_* value * @param int[] $stabilityFlags array of package name => BasePackage::STABILITY_* value * @param array[] $rootAliases array of package => version => [alias, alias_normalized] * @param string[] $rootReferences * @param BasePackage[] $packages * @param BasePackage[] $unacceptableFixedPackages * * @phpstan-param array<string, BasePackage::STABILITY_*> $acceptableStabilities * @phpstan-param array<string, BasePackage::STABILITY_*> $stabilityFlags * @phpstan-param array<string, array<string, array{alias: string, alias_normalized: string}>> $rootAliases * @phpstan-param array<string, string> $rootReferences */ public function __construct(string $name, array $repositories, Request $request, array $acceptableStabilities, array $stabilityFlags, array $rootAliases, array $rootReferences, array $packages, array $unacceptableFixedPackages) { parent::__construct($name); $this->repositories = $repositories; $this->request = $request; $this->acceptableStabilities = $acceptableStabilities; $this->stabilityFlags = $stabilityFlags; $this->rootAliases = $rootAliases; $this->rootReferences = $rootReferences; $this->packages = $packages; $this->unacceptableFixedPackages = $unacceptableFixedPackages; } /** * @return RepositoryInterface[] */ public function getRepositories(): array { return $this->repositories; } public function getRequest(): Request { return $this->request; } /** * @return int[] array of stability => BasePackage::STABILITY_* value * @phpstan-return array<string, BasePackage::STABILITY_*> */ public function getAcceptableStabilities(): array { return $this->acceptableStabilities; } /** * @return int[] array of package name => BasePackage::STABILITY_* value * @phpstan-return array<string, BasePackage::STABILITY_*> */ public function getStabilityFlags(): array { return $this->stabilityFlags; } /** * @return array[] of package => version => [alias, alias_normalized] * @phpstan-return array<string, array<string, array{alias: string, alias_normalized: string}>> */ public function getRootAliases(): array { return $this->rootAliases; } /** * @return string[] * @phpstan-return array<string, string> */ public function getRootReferences(): array { return $this->rootReferences; } /** * @return BasePackage[] */ public function getPackages(): array { return $this->packages; } /** * @return BasePackage[] */ public function getUnacceptableFixedPackages(): array { return $this->unacceptableFixedPackages; } /** * @param BasePackage[] $packages */ public function setPackages(array $packages): void { $this->packages = $packages; } /** * @param BasePackage[] $packages */ public function setUnacceptableFixedPackages(array $packages): void { $this->unacceptableFixedPackages = $packages; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Plugin/CommandEvent.php
src/Composer/Plugin/CommandEvent.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\Plugin; use Composer\EventDispatcher\Event; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * An event for all commands. * * @author Nils Adermann <naderman@naderman.de> */ class CommandEvent extends Event { /** * @var string */ private $commandName; /** * @var InputInterface */ private $input; /** * @var OutputInterface */ private $output; /** * Constructor. * * @param string $name The event name * @param string $commandName The command name * @param mixed[] $args Arguments passed by the user * @param mixed[] $flags Optional flags to pass data not as argument */ public function __construct(string $name, string $commandName, InputInterface $input, OutputInterface $output, array $args = [], array $flags = []) { parent::__construct($name, $args, $flags); $this->commandName = $commandName; $this->input = $input; $this->output = $output; } /** * Returns the command input interface */ public function getInput(): InputInterface { return $this->input; } /** * Retrieves the command output interface */ public function getOutput(): OutputInterface { return $this->output; } /** * Retrieves the name of the command being run */ public function getCommandName(): string { return $this->commandName; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Plugin/Capability/CommandProvider.php
src/Composer/Plugin/Capability/CommandProvider.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\Plugin\Capability; /** * Commands Provider Interface * * This capability will receive an array with 'composer' and 'io' keys as * constructor argument. Those contain Composer\Composer and Composer\IO\IOInterface * instances. It also contains a 'plugin' key containing the plugin instance that * created the capability. * * @author Jérémy Derussé <jeremy@derusse.com> */ interface CommandProvider extends Capability { /** * Retrieves an array of commands * * @return \Composer\Command\BaseCommand[] */ public function getCommands(); }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Plugin/Capability/Capability.php
src/Composer/Plugin/Capability/Capability.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\Plugin\Capability; /** * Marker interface for Plugin capabilities. * Every new Capability which is added to the Plugin API must implement this interface. * * @api */ interface Capability { }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/EventDispatcher/EventSubscriberInterface.php
src/Composer/EventDispatcher/EventSubscriberInterface.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\EventDispatcher; /** * An EventSubscriber knows which events it is interested in. * * If an EventSubscriber is added to an EventDispatcher, the manager invokes * {@link getSubscribedEvents} and registers the subscriber as a listener for all * returned events. * * @author Guilherme Blanco <guilhermeblanco@hotmail.com> * @author Jonathan Wage <jonwage@gmail.com> * @author Roman Borschel <roman@code-factory.org> * @author Bernhard Schussek <bschussek@gmail.com> */ interface EventSubscriberInterface { /** * Returns an array of event names this subscriber wants to listen to. * * The array keys are event names and the value can be: * * * The method name to call (priority defaults to 0) * * An array composed of the method name to call and the priority * * An array of arrays composed of the method names to call and respective * priorities, or 0 if unset * * For instance: * * * array('eventName' => 'methodName') * * array('eventName' => array('methodName', $priority)) * * array('eventName' => array(array('methodName1', $priority), array('methodName2')) * * @return array<string, string|array{0: string, 1?: int}|array<array{0: string, 1?: int}>> The event names to listen to */ public static function getSubscribedEvents(); }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/EventDispatcher/ScriptExecutionException.php
src/Composer/EventDispatcher/ScriptExecutionException.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\EventDispatcher; /** * Thrown when a script running an external process exits with a non-0 status code * * @author Jordi Boggiano <j.boggiano@seld.be> */ class ScriptExecutionException extends \RuntimeException { }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/EventDispatcher/EventDispatcher.php
src/Composer/EventDispatcher/EventDispatcher.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\EventDispatcher; use Composer\DependencyResolver\Transaction; use Composer\Installer\InstallerEvent; use Composer\IO\ConsoleIO; use Composer\IO\IOInterface; use Composer\Composer; use Composer\Package\PackageInterface; use Composer\PartialComposer; use Composer\Pcre\Preg; use Composer\Plugin\CommandEvent; use Composer\Plugin\PreCommandRunEvent; use Composer\Util\Platform; use Composer\DependencyResolver\Operation\OperationInterface; use Composer\Repository\RepositoryInterface; use Composer\Script; use Composer\Installer\PackageEvent; use Composer\Installer\BinaryInstaller; use Composer\Util\ProcessExecutor; use Composer\Script\Event as ScriptEvent; use Composer\Autoload\ClassLoader; use Symfony\Component\Console\Application; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\StringInput; use Symfony\Component\Console\Output\ConsoleOutput; use Symfony\Component\Process\PhpExecutableFinder; use Symfony\Component\Process\ExecutableFinder; /** * The Event Dispatcher. * * Example in command: * $dispatcher = new EventDispatcher($this->requireComposer(), $this->getApplication()->getIO()); * // ... * $dispatcher->dispatch(ScriptEvents::POST_INSTALL_CMD); * // ... * * @author François Pluchino <francois.pluchino@opendisplay.com> * @author Jordi Boggiano <j.boggiano@seld.be> * @author Nils Adermann <naderman@naderman.de> */ class EventDispatcher { /** @var PartialComposer */ protected $composer; /** @var IOInterface */ protected $io; /** @var ?ClassLoader */ protected $loader; /** @var ProcessExecutor */ protected $process; /** @var array<string, array<int, array<callable|string>>> */ protected $listeners = []; /** @var bool */ protected $runScripts = true; /** @var list<string> */ private $eventStack; /** @var list<string> */ private $skipScripts; /** @var string|null */ private $previousHash = null; /** @var array<string, true> */ private $previousListeners = []; /** * Constructor. * * @param PartialComposer $composer The composer instance * @param IOInterface $io The IOInterface instance */ public function __construct(PartialComposer $composer, IOInterface $io, ?ProcessExecutor $process = null) { $this->composer = $composer; $this->io = $io; $this->process = $process ?? new ProcessExecutor($io); $this->eventStack = []; $this->skipScripts = array_values(array_filter( array_map('trim', explode(',', (string) Platform::getEnv('COMPOSER_SKIP_SCRIPTS'))), static function ($val) { return $val !== ''; } )); } /** * Set whether script handlers are active or not * * @return $this */ public function setRunScripts(bool $runScripts = true): self { $this->runScripts = $runScripts; return $this; } /** * Dispatch an event * * @param string|null $eventName The event name, required if no $event is provided * @param Event $event An event instance, required if no $eventName is provided * @return int return code of the executed script if any, for php scripts a false return * value is changed to 1, anything else to 0 */ public function dispatch(?string $eventName, ?Event $event = null): int { if (null === $event) { if (null === $eventName) { throw new \InvalidArgumentException('If no $event is passed in to '.__METHOD__.' you have to pass in an $eventName, got null.'); } $event = new Event($eventName); } return $this->doDispatch($event); } /** * Dispatch a script event. * * @param string $eventName The constant in ScriptEvents * @param array<int, mixed> $additionalArgs Arguments passed by the user * @param array<string, mixed> $flags Optional flags to pass data not as argument * @return int return code of the executed script if any, for php scripts a false return * value is changed to 1, anything else to 0 */ public function dispatchScript(string $eventName, bool $devMode = false, array $additionalArgs = [], array $flags = []): int { assert($this->composer instanceof Composer, new \LogicException('This should only be reached with a fully loaded Composer')); return $this->doDispatch(new ScriptEvent($eventName, $this->composer, $this->io, $devMode, $additionalArgs, $flags)); } /** * Dispatch a package event. * * @param string $eventName The constant in PackageEvents * @param bool $devMode Whether or not we are in dev mode * @param RepositoryInterface $localRepo The installed repository * @param OperationInterface[] $operations The list of operations * @param OperationInterface $operation The package being installed/updated/removed * * @return int return code of the executed script if any, for php scripts a false return * value is changed to 1, anything else to 0 */ public function dispatchPackageEvent(string $eventName, bool $devMode, RepositoryInterface $localRepo, array $operations, OperationInterface $operation): int { assert($this->composer instanceof Composer, new \LogicException('This should only be reached with a fully loaded Composer')); return $this->doDispatch(new PackageEvent($eventName, $this->composer, $this->io, $devMode, $localRepo, $operations, $operation)); } /** * Dispatch a installer event. * * @param string $eventName The constant in InstallerEvents * @param bool $devMode Whether or not we are in dev mode * @param bool $executeOperations True if operations will be executed, false in --dry-run * @param Transaction $transaction The transaction contains the list of operations * * @return int return code of the executed script if any, for php scripts a false return * value is changed to 1, anything else to 0 */ public function dispatchInstallerEvent(string $eventName, bool $devMode, bool $executeOperations, Transaction $transaction): int { assert($this->composer instanceof Composer, new \LogicException('This should only be reached with a fully loaded Composer')); return $this->doDispatch(new InstallerEvent($eventName, $this->composer, $this->io, $devMode, $executeOperations, $transaction)); } /** * Triggers the listeners of an event. * * @param Event $event The event object to pass to the event handlers/listeners. * @throws \RuntimeException|\Exception * @return int return code of the executed script if any, for php scripts a false return * value is changed to 1, anything else to 0 */ protected function doDispatch(Event $event) { if (Platform::getEnv('COMPOSER_DEBUG_EVENTS')) { $details = null; if ($event instanceof PackageEvent) { $details = (string) $event->getOperation(); } elseif ($event instanceof CommandEvent) { $details = $event->getCommandName(); } elseif ($event instanceof PreCommandRunEvent) { $details = $event->getCommand(); } $this->io->writeError('Dispatching <info>'.$event->getName().'</info>'.($details ? ' ('.$details.')' : '').' event'); } $listeners = $this->getListeners($event); $this->pushEvent($event); $autoloadersBefore = spl_autoload_functions(); try { $returnMax = 0; foreach ($listeners as $callable) { $return = 0; $this->ensureBinDirIsInPath(); $additionalArgs = $event->getArguments(); if (is_string($callable) && str_contains($callable, '@no_additional_args')) { $callable = Preg::replace('{ ?@no_additional_args}', '', $callable); $additionalArgs = []; } $formattedEventNameWithArgs = $event->getName() . ($additionalArgs !== [] ? ' (' . implode(', ', $additionalArgs) . ')' : ''); if (!is_string($callable)) { $this->makeAutoloader($event, $callable); if (!is_callable($callable)) { $className = is_object($callable[0]) ? get_class($callable[0]) : $callable[0]; throw new \RuntimeException('Subscriber '.$className.'::'.$callable[1].' for event '.$event->getName().' is not callable, make sure the function is defined and public'); } if (is_array($callable) && (is_string($callable[0]) || is_object($callable[0])) && is_string($callable[1])) { $this->io->writeError(sprintf('> %s: %s', $formattedEventNameWithArgs, (is_object($callable[0]) ? get_class($callable[0]) : $callable[0]).'->'.$callable[1]), true, IOInterface::VERBOSE); } $return = false === $callable($event) ? 1 : 0; } elseif ($this->isComposerScript($callable)) { $this->io->writeError(sprintf('> %s: %s', $formattedEventNameWithArgs, $callable), true, IOInterface::VERBOSE); $script = explode(' ', substr($callable, 1)); $scriptName = $script[0]; unset($script[0]); $index = array_search('@additional_args', $script, true); if ($index !== false) { $args = array_splice($script, $index, 0, $additionalArgs); } else { $args = array_merge($script, $additionalArgs); } $flags = $event->getFlags(); if (isset($flags['script-alias-input'])) { $argsString = implode(' ', array_map(static function ($arg) { return ProcessExecutor::escape($arg); }, $script)); $flags['script-alias-input'] = $argsString . ' ' . $flags['script-alias-input']; unset($argsString); } if (strpos($callable, '@composer ') === 0) { $exec = $this->getPhpExecCommand() . ' ' . ProcessExecutor::escape(Platform::getEnv('COMPOSER_BINARY')) . ' ' . implode(' ', $args); if (0 !== ($exitCode = $this->executeTty($exec))) { $this->io->writeError(sprintf('<error>Script %s handling the %s event returned with error code '.$exitCode.'</error>', $callable, $event->getName()), true, IOInterface::QUIET); throw new ScriptExecutionException('Error Output: '.$this->process->getErrorOutput(), $exitCode); } } else { if (!$this->getListeners(new Event($scriptName))) { $this->io->writeError(sprintf('<warning>You made a reference to a non-existent script %s</warning>', $callable), true, IOInterface::QUIET); } try { /** @var InstallerEvent $event */ $scriptEvent = new ScriptEvent($scriptName, $event->getComposer(), $event->getIO(), $event->isDevMode(), $args, $flags); $scriptEvent->setOriginatingEvent($event); $return = $this->dispatch($scriptName, $scriptEvent); } catch (ScriptExecutionException $e) { $this->io->writeError(sprintf('<error>Script %s was called via %s</error>', $callable, $event->getName()), true, IOInterface::QUIET); throw $e; } } } elseif ($this->isPhpScript($callable)) { $className = substr($callable, 0, strpos($callable, '::')); $methodName = substr($callable, strpos($callable, '::') + 2); $this->makeAutoloader($event, $callable); if (!class_exists($className)) { $this->io->writeError('<warning>Class '.$className.' is not autoloadable, can not call '.$event->getName().' script</warning>', true, IOInterface::QUIET); continue; } if (!is_callable($callable)) { $this->io->writeError('<warning>Method '.$callable.' is not callable, can not call '.$event->getName().' script</warning>', true, IOInterface::QUIET); continue; } try { $return = false === $this->executeEventPhpScript($className, $methodName, $event) ? 1 : 0; } catch (\Exception $e) { $message = "Script %s handling the %s event terminated with an exception"; $this->io->writeError('<error>'.sprintf($message, $callable, $event->getName()).'</error>', true, IOInterface::QUIET); throw $e; } } elseif ($this->isCommandClass($callable)) { $className = $callable; $this->makeAutoloader($event, [$callable, 'run']); if (!class_exists($className)) { $this->io->writeError('<warning>Class '.$className.' is not autoloadable, can not call '.$event->getName().' script</warning>', true, IOInterface::QUIET); continue; } if (!is_a($className, Command::class, true)) { $this->io->writeError('<warning>Class '.$className.' does not extend '.Command::class.', can not call '.$event->getName().' script</warning>', true, IOInterface::QUIET); continue; } if (defined('Composer\Script\ScriptEvents::'.str_replace('-', '_', strtoupper($event->getName())))) { $this->io->writeError('<warning>You cannot bind '.$event->getName().' to a Command class, use a non-reserved name</warning>', true, IOInterface::QUIET); continue; } $app = new Application(); $app->setCatchExceptions(false); if (method_exists($app, 'setCatchErrors')) { $app->setCatchErrors(false); } $app->setAutoExit(false); $cmd = new $className($event->getName()); // @phpstan-ignore method.notFound, function.alreadyNarrowedType if (method_exists($app, 'addCommand')) { $app->addCommand($cmd); } else { // Compatibility layer for symfony/console <7.4 // @phpstan-ignore method.notFound $app->add($cmd); } $app->setDefaultCommand((string) $cmd->getName(), true); try { $args = implode(' ', array_map(static function ($arg) { return ProcessExecutor::escape($arg); }, $additionalArgs)); // reusing the output from $this->io is mostly needed for tests, but generally speaking // it does not hurt to keep the same stream as the current Application if ($this->io instanceof ConsoleIO) { $reflProp = new \ReflectionProperty($this->io, 'output'); if (\PHP_VERSION_ID < 80100) { $reflProp->setAccessible(true); } $output = $reflProp->getValue($this->io); } else { $output = new ConsoleOutput(); } $return = $app->run(new StringInput($event->getFlags()['script-alias-input'] ?? $args), $output); } catch (\Exception $e) { $message = "Script %s handling the %s event terminated with an exception"; $this->io->writeError('<error>'.sprintf($message, $callable, $event->getName()).'</error>', true, IOInterface::QUIET); throw $e; } } else { $args = implode(' ', array_map(['Composer\Util\ProcessExecutor', 'escape'], $additionalArgs)); // @putenv does not receive arguments if (strpos($callable, '@putenv ') === 0) { $exec = $callable; } else { if (str_contains($callable, '@additional_args')) { $exec = str_replace('@additional_args', $args, $callable); } else { $exec = $callable . ($args === '' ? '' : ' '.$args); } } if ($this->io->isVerbose()) { $this->io->writeError(sprintf('> %s: %s', $event->getName(), $exec)); } elseif ( // do not output the command being run when using `composer exec` as it is fairly obvious the user is running it $event->getName() !== '__exec_command' // do not output the command being run when using `composer <script-name>` as it is also fairly obvious the user is running it && ($event->getFlags()['script-alias-input'] ?? null) === null ) { $this->io->writeError(sprintf('> %s', $exec)); } $possibleLocalBinaries = $this->composer->getPackage()->getBinaries(); if (count($possibleLocalBinaries) > 0) { foreach ($possibleLocalBinaries as $localExec) { if (Preg::isMatch('{\b'.preg_quote($callable).'$}', $localExec)) { $caller = BinaryInstaller::determineBinaryCaller($localExec); $exec = Preg::replace('{^'.preg_quote($callable).'}', $caller . ' ' . $localExec, $exec); break; } } } if (strpos($exec, '@putenv ') === 0) { if (false === strpos($exec, '=')) { Platform::clearEnv(substr($exec, 8)); } else { [$var, $value] = explode('=', substr($exec, 8), 2); Platform::putEnv($var, $value); } continue; } if (strpos($exec, '@php ') === 0) { $pathAndArgs = substr($exec, 5); if (Platform::isWindows()) { $pathAndArgs = Preg::replaceCallback('{^\S+}', static function ($path) { return str_replace('/', '\\', $path[0]); }, $pathAndArgs); } // match somename (not in quote, and not a qualified path) and if it is not a valid path from CWD then try to find it // in $PATH. This allows support for `@php foo` where foo is a binary name found in PATH but not an actual relative path $matched = Preg::isMatchStrictGroups('{^[^\'"\s/\\\\]+}', $pathAndArgs, $match); if ($matched && !file_exists($match[0])) { $finder = new ExecutableFinder; if ($pathToExec = $finder->find($match[0])) { if (Platform::isWindows()) { $execWithoutExt = Preg::replace('{\.(exe|bat|cmd|com)$}i', '', $pathToExec); // prefer non-extension file if it exists when executing with PHP if (file_exists($execWithoutExt)) { $pathToExec = $execWithoutExt; } unset($execWithoutExt); } $pathAndArgs = $pathToExec . substr($pathAndArgs, strlen($match[0])); } } $exec = $this->getPhpExecCommand() . ' ' . $pathAndArgs; } else { $finder = new PhpExecutableFinder(); $phpPath = $finder->find(false); if ($phpPath) { Platform::putEnv('PHP_BINARY', $phpPath); } if (Platform::isWindows()) { $exec = Preg::replaceCallback('{^\S+}', static function ($path) { return str_replace('/', '\\', $path[0]); }, $exec); } } // if composer is being executed, make sure it runs the expected composer from current path // resolution, even if bin-dir contains composer too because the project requires composer/composer // see https://github.com/composer/composer/issues/8748 if (strpos($exec, 'composer ') === 0) { $exec = $this->getPhpExecCommand() . ' ' . ProcessExecutor::escape(Platform::getEnv('COMPOSER_BINARY')) . substr($exec, 8); } if (0 !== ($exitCode = $this->executeTty($exec))) { $this->io->writeError(sprintf('<error>Script %s handling the %s event returned with error code '.$exitCode.'</error>', $callable, $event->getName()), true, IOInterface::QUIET); throw new ScriptExecutionException('Error Output: '.$this->process->getErrorOutput(), $exitCode); } } $returnMax = max($returnMax, $return); if ($event->isPropagationStopped()) { break; } } } finally { $this->popEvent(); $knownIdentifiers = []; foreach ($autoloadersBefore as $key => $cb) { $knownIdentifiers[$this->getCallbackIdentifier($cb)] = ['key' => $key, 'callback' => $cb]; } foreach (spl_autoload_functions() as $cb) { // once we get to the first known autoloader, we can leave any appended autoloader without problems if (isset($knownIdentifiers[$this->getCallbackIdentifier($cb)]) && $knownIdentifiers[$this->getCallbackIdentifier($cb)]['key'] === 0) { break; } // other newly appeared prepended autoloaders should be appended instead to ensure Composer loads its classes first if ($cb instanceof ClassLoader) { $cb->unregister(); $cb->register(false); } else { spl_autoload_unregister($cb); spl_autoload_register($cb); } } } return $returnMax; } protected function executeTty(string $exec): int { if ($this->io->isInteractive()) { return $this->process->executeTty($exec); } return $this->process->execute($exec); } protected function getPhpExecCommand(): string { $finder = new PhpExecutableFinder(); $phpPath = $finder->find(false); if (!$phpPath) { throw new \RuntimeException('Failed to locate PHP binary to execute '.$phpPath); } $phpArgs = $finder->findArguments(); $phpArgs = \count($phpArgs) > 0 ? ' ' . implode(' ', $phpArgs) : ''; $allowUrlFOpenFlag = ' -d allow_url_fopen=' . ProcessExecutor::escape(ini_get('allow_url_fopen')); $disableFunctionsFlag = ' -d disable_functions=' . ProcessExecutor::escape(ini_get('disable_functions')); $memoryLimitFlag = ' -d memory_limit=' . ProcessExecutor::escape(ini_get('memory_limit')); return ProcessExecutor::escape($phpPath) . $phpArgs . $allowUrlFOpenFlag . $disableFunctionsFlag . $memoryLimitFlag; } /** * @param Event $event Event invoking the PHP callable * * @return mixed */ protected function executeEventPhpScript(string $className, string $methodName, Event $event) { if ($this->io->isVerbose()) { $this->io->writeError(sprintf('> %s: %s::%s', $event->getName(), $className, $methodName)); } else { $this->io->writeError(sprintf('> %s::%s', $className, $methodName)); } return $className::$methodName($event); } /** * Add a listener for a particular event * * @param string $eventName The event name - typically a constant * @param callable|string $listener A callable expecting an event argument, or a command string to be executed (same as a composer.json "scripts" entry) * @param int $priority A higher value represents a higher priority */ public function addListener(string $eventName, $listener, int $priority = 0): void { $this->listeners[$eventName][$priority][] = $listener; } /** * @param callable|object $listener A callable or an object instance for which all listeners should be removed */ public function removeListener($listener): void { foreach ($this->listeners as $eventName => $priorities) { foreach ($priorities as $priority => $listeners) { foreach ($listeners as $index => $candidate) { if ($listener === $candidate || (is_array($candidate) && is_object($listener) && $candidate[0] === $listener)) { unset($this->listeners[$eventName][$priority][$index]); } } } } } /** * Adds object methods as listeners for the events in getSubscribedEvents * * @see EventSubscriberInterface */ public function addSubscriber(EventSubscriberInterface $subscriber): void { foreach ($subscriber->getSubscribedEvents() as $eventName => $params) { if (is_string($params)) { $this->addListener($eventName, [$subscriber, $params]); } elseif (is_string($params[0])) { $this->addListener($eventName, [$subscriber, $params[0]], $params[1] ?? 0); } else { foreach ($params as $listener) { $this->addListener($eventName, [$subscriber, $listener[0]], $listener[1] ?? 0); } } } } /** * Retrieves all listeners for a given event * * @return array<callable|string> All listeners: callables and scripts */ protected function getListeners(Event $event): array { $scriptListeners = $this->runScripts ? $this->getScriptListeners($event) : []; if (!isset($this->listeners[$event->getName()][0])) { $this->listeners[$event->getName()][0] = []; } krsort($this->listeners[$event->getName()]); $listeners = $this->listeners; $listeners[$event->getName()][0] = array_merge($listeners[$event->getName()][0], $scriptListeners); return array_merge(...$listeners[$event->getName()]); } /** * Checks if an event has listeners registered */ public function hasEventListeners(Event $event): bool { $listeners = $this->getListeners($event); return count($listeners) > 0; } /** * Finds all listeners defined as scripts in the package * * @param Event $event Event object * @return string[] Listeners */ protected function getScriptListeners(Event $event): array { $package = $this->composer->getPackage(); $scripts = $package->getScripts(); if (empty($scripts[$event->getName()])) { return []; } if (in_array($event->getName(), $this->skipScripts, true)) { $this->io->writeError('Skipped script listeners for <info>'.$event->getName().'</info> because of COMPOSER_SKIP_SCRIPTS', true, IOInterface::VERBOSE); return []; } return $scripts[$event->getName()]; } /** * Checks if string given references a class path and method */ protected function isPhpScript(string $callable): bool { return false === strpos($callable, ' ') && false !== strpos($callable, '::'); } /** * Checks if string given references a command class */ protected function isCommandClass(string $callable): bool { return str_contains($callable, '\\') && !str_contains($callable, ' ') && str_ends_with($callable, 'Command'); } /** * Checks if string given references a composer run-script */ protected function isComposerScript(string $callable): bool { return str_starts_with($callable, '@') && !str_starts_with($callable, '@php ') && !str_starts_with($callable, '@putenv '); } /** * Push an event to the stack of active event * * @throws \RuntimeException */ protected function pushEvent(Event $event): int { $eventName = $event->getName(); if (in_array($eventName, $this->eventStack)) { throw new \RuntimeException(sprintf("Circular call to script handler '%s' detected", $eventName)); } return array_push($this->eventStack, $eventName); } /** * Pops the active event from the stack */ protected function popEvent(): ?string { return array_pop($this->eventStack); } private function ensureBinDirIsInPath(): void { $pathEnv = 'PATH'; // checking if only Path and not PATH is set then we probably need to update the Path env // on Windows getenv is case-insensitive so we cannot check it via Platform::getEnv and // we need to check in $_SERVER directly if (!isset($_SERVER[$pathEnv]) && isset($_SERVER['Path'])) { $pathEnv = 'Path'; } // add the bin dir to the PATH to make local binaries of deps usable in scripts $binDir = $this->composer->getConfig()->get('bin-dir'); if (is_dir($binDir)) { $binDir = realpath($binDir); $pathValue = (string) Platform::getEnv($pathEnv); if (!Preg::isMatch('{(^|'.PATH_SEPARATOR.')'.preg_quote($binDir).'($|'.PATH_SEPARATOR.')}', $pathValue)) { Platform::putEnv($pathEnv, $binDir.PATH_SEPARATOR.$pathValue); } } } /** * @param callable $cb DO NOT MOVE TO TYPE HINT as private autoload callbacks are not technically callable */ private function getCallbackIdentifier($cb): string { if (is_string($cb)) { return 'fn:'.$cb; } if (is_object($cb)) { return 'obj:'.spl_object_hash($cb); } if (is_array($cb)) { return 'array:'.(is_string($cb[0]) ? $cb[0] : get_class($cb[0]) .'#'.spl_object_hash($cb[0])).'::'.$cb[1]; } // not great but also do not want to break everything here return 'unsupported'; } /** * @param mixed $callable Technically a callable shape but as the class may not be autoloadable yet PHP might not see it this way, so we cannot type hint as such */ private function makeAutoloader(Event $event, $callable): void {
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
true
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/EventDispatcher/Event.php
src/Composer/EventDispatcher/Event.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\EventDispatcher; /** * The base event class * * @author Nils Adermann <naderman@naderman.de> */ class Event { /** * @var string This event's name */ protected $name; /** * @var string[] Arguments passed by the user, these will be forwarded to CLI script handlers */ protected $args; /** * @var mixed[] Flags usable in PHP script handlers */ protected $flags; /** * @var bool Whether the event should not be passed to more listeners */ private $propagationStopped = false; /** * Constructor. * * @param string $name The event name * @param string[] $args Arguments passed by the user * @param mixed[] $flags Optional flags to pass data not as argument */ public function __construct(string $name, array $args = [], array $flags = []) { $this->name = $name; $this->args = $args; $this->flags = $flags; } /** * Returns the event's name. * * @return string The event name */ public function getName(): string { return $this->name; } /** * Returns the event's arguments. * * @return string[] The event arguments */ public function getArguments(): array { return $this->args; } /** * Returns the event's flags. * * @return mixed[] The event flags */ public function getFlags(): array { return $this->flags; } /** * Checks if stopPropagation has been called * * @return bool Whether propagation has been stopped */ public function isPropagationStopped(): bool { return $this->propagationStopped; } /** * Prevents the event from being passed to further listeners */ public function stopPropagation(): void { $this->propagationStopped = true; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Console/HtmlOutputFormatter.php
src/Composer/Console/HtmlOutputFormatter.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\Console; use Closure; use Composer\Pcre\Preg; use Symfony\Component\Console\Formatter\OutputFormatter; use Symfony\Component\Console\Formatter\OutputFormatterStyle; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class HtmlOutputFormatter extends OutputFormatter { /** @var array<int, string> */ private static $availableForegroundColors = [ 30 => 'black', 31 => 'red', 32 => 'green', 33 => 'yellow', 34 => 'blue', 35 => 'magenta', 36 => 'cyan', 37 => 'white', ]; /** @var array<int, string> */ private static $availableBackgroundColors = [ 40 => 'black', 41 => 'red', 42 => 'green', 43 => 'yellow', 44 => 'blue', 45 => 'magenta', 46 => 'cyan', 47 => 'white', ]; /** @var array<int, string> */ private static $availableOptions = [ 1 => 'bold', 4 => 'underscore', //5 => 'blink', //7 => 'reverse', //8 => 'conceal' ]; /** * @param array<string, OutputFormatterStyle> $styles Array of "name => FormatterStyle" instances */ public function __construct(array $styles = []) { parent::__construct(true, $styles); } public function format(?string $message): ?string { $formatted = parent::format($message); if ($formatted === null) { return null; } $clearEscapeCodes = '(?:39|49|0|22|24|25|27|28)'; return Preg::replaceCallback("{\033\[([0-9;]+)m(.*?)\033\[(?:".$clearEscapeCodes.";)*?".$clearEscapeCodes."m}s", Closure::fromCallable([$this, 'formatHtml']), $formatted); } /** * @param array<string|null> $matches */ private function formatHtml(array $matches): string { assert(is_string($matches[1])); $out = '<span style="'; foreach (explode(';', $matches[1]) as $code) { if (isset(self::$availableForegroundColors[(int) $code])) { $out .= 'color:'.self::$availableForegroundColors[(int) $code].';'; } elseif (isset(self::$availableBackgroundColors[(int) $code])) { $out .= 'background-color:'.self::$availableBackgroundColors[(int) $code].';'; } elseif (isset(self::$availableOptions[(int) $code])) { switch (self::$availableOptions[(int) $code]) { case 'bold': $out .= 'font-weight:bold;'; break; case 'underscore': $out .= 'text-decoration:underline;'; break; } } } return $out.'">'.$matches[2].'</span>'; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Console/Application.php
src/Composer/Console/Application.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Console; use Composer\Installer; use Composer\IO\NullIO; use Composer\Util\Filesystem; use Composer\Util\Platform; use Composer\Util\Silencer; use LogicException; use RuntimeException; use Symfony\Component\Console\Application as BaseApplication; use Symfony\Component\Console\Command\Command as SymfonyCommand; use Symfony\Component\Console\Exception\CommandNotFoundException; use Symfony\Component\Console\Exception\ExceptionInterface; use Symfony\Component\Console\Helper\HelperSet; use Symfony\Component\Console\Helper\QuestionHelper; use Symfony\Component\Console\Input\InputDefinition; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\ConsoleOutputInterface; use Symfony\Component\Console\Output\OutputInterface; use Seld\JsonLint\ParsingException; use Composer\Command; use Composer\Composer; use Composer\Factory; use Composer\Downloader\TransportException; use Composer\IO\IOInterface; use Composer\IO\ConsoleIO; use Composer\Json\JsonValidationException; use Composer\Util\ErrorHandler; use Composer\Util\HttpDownloader; use Composer\EventDispatcher\ScriptExecutionException; use Composer\Exception\NoSslException; use Composer\XdebugHandler\XdebugHandler; use Symfony\Component\Process\Exception\ProcessTimedOutException; /** * The console application that handles the commands * * @author Ryan Weaver <ryan@knplabs.com> * @author Jordi Boggiano <j.boggiano@seld.be> * @author François Pluchino <francois.pluchino@opendisplay.com> */ class Application extends BaseApplication { /** * @var ?Composer */ protected $composer; /** * @var IOInterface */ protected $io; /** @var string */ private static $logo = ' ______ / ____/___ ____ ___ ____ ____ ________ _____ / / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/ / /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ / \____/\____/_/ /_/ /_/ .___/\____/____/\___/_/ /_/ '; /** @var bool */ private $hasPluginCommands = false; /** @var bool */ private $disablePluginsByDefault = false; /** @var bool */ private $disableScriptsByDefault = false; /** * @var string|false Store the initial working directory at startup time */ private $initialWorkingDirectory; public function __construct(string $name = 'Composer', string $version = '') { if (method_exists($this, 'setCatchErrors')) { $this->setCatchErrors(true); } static $shutdownRegistered = false; if ($version === '') { $version = Composer::getVersion(); } if (function_exists('ini_set') && extension_loaded('xdebug')) { ini_set('xdebug.show_exception_trace', '0'); ini_set('xdebug.scream', '0'); } if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) { date_default_timezone_set(Silencer::call('date_default_timezone_get')); } $this->io = new NullIO(); if (!$shutdownRegistered) { $shutdownRegistered = true; register_shutdown_function(static function (): void { $lastError = error_get_last(); if ($lastError && $lastError['message'] && (strpos($lastError['message'], 'Allowed memory') !== false /*Zend PHP out of memory error*/ || strpos($lastError['message'], 'exceeded memory') !== false /*HHVM out of memory errors*/)) { echo "\n". 'Check https://getcomposer.org/doc/articles/troubleshooting.md#memory-limit-errors for more info on how to handle out of memory errors.'; } }); } $this->initialWorkingDirectory = getcwd(); parent::__construct($name, $version); } public function __destruct() { } public function run(?InputInterface $input = null, ?OutputInterface $output = null): int { if (null === $output) { $output = Factory::createOutput(); } return parent::run($input, $output); } public function doRun(InputInterface $input, OutputInterface $output): int { $this->disablePluginsByDefault = $input->hasParameterOption('--no-plugins'); $this->disableScriptsByDefault = $input->hasParameterOption('--no-scripts'); static $stdin = null; if (null === $stdin) { $stdin = defined('STDIN') ? STDIN : fopen('php://stdin', 'r'); } if (Platform::getEnv('COMPOSER_TESTS_ARE_RUNNING') !== '1' && (Platform::getEnv('COMPOSER_NO_INTERACTION') || $stdin === false || !Platform::isTty($stdin))) { $input->setInteractive(false); } $io = $this->io = new ConsoleIO($input, $output, new HelperSet([ new QuestionHelper(), ])); // Register error handler again to pass it the IO instance ErrorHandler::register($io); if ($input->hasParameterOption('--no-cache')) { $io->writeError('Disabling cache usage', true, IOInterface::DEBUG); Platform::putEnv('COMPOSER_CACHE_DIR', Platform::isWindows() ? 'nul' : '/dev/null'); } // switch working dir $newWorkDir = $this->getNewWorkingDir($input); if (null !== $newWorkDir) { $oldWorkingDir = Platform::getCwd(true); chdir($newWorkDir); $this->initialWorkingDirectory = $newWorkDir; $cwd = Platform::getCwd(true); $io->writeError('Changed CWD to ' . ($cwd !== '' ? $cwd : $newWorkDir), true, IOInterface::DEBUG); } // determine command name to be executed without including plugin commands $commandName = ''; if ($name = $this->getCommandNameBeforeBinding($input)) { try { $commandName = $this->find($name)->getName(); } catch (CommandNotFoundException $e) { // we'll check command validity again later after plugins are loaded $commandName = false; } catch (\InvalidArgumentException $e) { } } // prompt user for dir change if no composer.json is present in current dir if ( null === $newWorkDir // do not prompt for commands that can function without composer.json && !in_array($commandName, ['', 'list', 'init', 'about', 'help', 'diagnose', 'self-update', 'global', 'create-project', 'outdated'], true) && !file_exists(Factory::getComposerFile()) // if use-parent-dir is disabled we should not prompt && ($useParentDirIfNoJsonAvailable = $this->getUseParentDirConfigValue()) !== false // config --file ... should not prompt && ($commandName !== 'config' || ($input->hasParameterOption('--file', true) === false && $input->hasParameterOption('-f', true) === false)) // calling a command's help should not prompt && $input->hasParameterOption('--help', true) === false && $input->hasParameterOption('-h', true) === false ) { $dir = dirname(Platform::getCwd(true)); $home = realpath(Platform::getEnv('HOME') ?: Platform::getEnv('USERPROFILE') ?: '/'); // abort when we reach the home dir or top of the filesystem while (dirname($dir) !== $dir && $dir !== $home) { if (file_exists($dir.'/'.Factory::getComposerFile())) { if ($useParentDirIfNoJsonAvailable !== true && !$io->isInteractive()) { $io->writeError('<info>No composer.json in current directory, to use the one at '.$dir.' run interactively or set config.use-parent-dir to true</info>'); break; } if ($useParentDirIfNoJsonAvailable === true || $io->askConfirmation('<info>No composer.json in current directory, do you want to use the one at '.$dir.'?</info> [<comment>y,n</comment>]? ')) { if ($useParentDirIfNoJsonAvailable === true) { $io->writeError('<info>No composer.json in current directory, changing working directory to '.$dir.'</info>'); } else { $io->writeError('<info>Always want to use the parent dir? Use "composer config --global use-parent-dir true" to change the default.</info>'); } $oldWorkingDir = Platform::getCwd(true); chdir($dir); } break; } $dir = dirname($dir); } unset($dir, $home); } $needsSudoCheck = !Platform::isWindows() && function_exists('exec') && !Platform::getEnv('COMPOSER_ALLOW_SUPERUSER') && !Platform::isDocker(); $isNonAllowedRoot = false; // Clobber sudo credentials if COMPOSER_ALLOW_SUPERUSER is not set before loading plugins if ($needsSudoCheck) { $isNonAllowedRoot = $this->isRunningAsRoot(); if ($isNonAllowedRoot) { if ($uid = (int) Platform::getEnv('SUDO_UID')) { // Silently clobber any sudo credentials on the invoking user to avoid privilege escalations later on // ref. https://github.com/composer/composer/issues/5119 Silencer::call('exec', "sudo -u \\#{$uid} sudo -K > /dev/null 2>&1"); } } // Silently clobber any remaining sudo leases on the current user as well to avoid privilege escalations Silencer::call('exec', 'sudo -K > /dev/null 2>&1'); } // avoid loading plugins/initializing the Composer instance earlier than necessary if no plugin command is needed // if showing the version, we never need plugin commands $mayNeedPluginCommand = false === $input->hasParameterOption(['--version', '-V']) && ( // not a composer command, so try loading plugin ones false === $commandName // list command requires plugin commands to show them || in_array($commandName, ['', 'list', 'help'], true) // autocompletion requires plugin commands but if we are running as root without COMPOSER_ALLOW_SUPERUSER // we'd rather not autocomplete plugins than abort autocompletion entirely, so we avoid loading plugins in this case || ($commandName === '_complete' && !$isNonAllowedRoot) ); if ($mayNeedPluginCommand && !$this->disablePluginsByDefault && !$this->hasPluginCommands) { // at this point plugins are needed, so if we are running as root and it is not allowed we need to prompt // if interactive, and abort otherwise if ($isNonAllowedRoot) { $io->writeError('<warning>Do not run Composer as root/super user! See https://getcomposer.org/root for details</warning>'); if ($io->isInteractive() && $io->askConfirmation('<info>Continue as root/super user</info> [<comment>yes</comment>]? ')) { // avoid a second prompt later $isNonAllowedRoot = false; } else { $io->writeError('<warning>Aborting as no plugin should be loaded if running as super user is not explicitly allowed</warning>'); return 1; } } try { foreach ($this->getPluginCommands() as $command) { if ($this->has($command->getName())) { $io->writeError('<warning>Plugin command '.$command->getName().' ('.get_class($command).') would override a Composer command and has been skipped</warning>'); } else { // Compatibility layer for symfony/console <7.4 // @phpstan-ignore method.notFound, function.alreadyNarrowedType method_exists($this, 'addCommand') ? $this->addCommand($command) : $this->add($command); } } } catch (NoSslException $e) { // suppress these as they are not relevant at this point } catch (ParsingException $e) { $details = $e->getDetails(); $file = realpath(Factory::getComposerFile()); $line = null; if ($details && isset($details['line'])) { $line = $details['line']; } $ghe = new GithubActionError($this->io); $ghe->emit($e->getMessage(), $file, $line); throw $e; } $this->hasPluginCommands = true; } if (!$this->disablePluginsByDefault && $isNonAllowedRoot && !$io->isInteractive()) { $io->writeError('<error>Composer plugins have been disabled for safety in this non-interactive session.</error>'); $io->writeError('<error>Set COMPOSER_ALLOW_SUPERUSER=1 if you want to allow plugins to run as root/super user.</error>'); $this->disablePluginsByDefault = true; } // determine command name to be executed incl plugin commands, and check if it's a proxy command $isProxyCommand = false; if ($name = $this->getCommandNameBeforeBinding($input)) { try { $command = $this->find($name); $commandName = $command->getName(); $isProxyCommand = ($command instanceof Command\BaseCommand && $command->isProxyCommand()); } catch (\InvalidArgumentException $e) { } } if (!$isProxyCommand) { $io->writeError(sprintf( 'Running %s (%s) with %s on %s', Composer::getVersion(), Composer::RELEASE_DATE, defined('HHVM_VERSION') ? 'HHVM '.HHVM_VERSION : 'PHP '.PHP_VERSION, function_exists('php_uname') ? php_uname('s') . ' / ' . php_uname('r') : 'Unknown OS' ), true, IOInterface::DEBUG); if (\PHP_VERSION_ID < 70205) { $io->writeError('<warning>Composer supports PHP 7.2.5 and above, you will most likely encounter problems with your PHP '.PHP_VERSION.'. Upgrading is strongly recommended but you can use Composer 2.2.x LTS as a fallback.</warning>'); } if (XdebugHandler::isXdebugActive() && !Platform::getEnv('COMPOSER_DISABLE_XDEBUG_WARN')) { $io->writeError('<warning>Composer is operating slower than normal because you have Xdebug enabled. See https://getcomposer.org/xdebug</warning>'); } if (defined('COMPOSER_DEV_WARNING_TIME') && $commandName !== 'self-update' && $commandName !== 'selfupdate' && time() > COMPOSER_DEV_WARNING_TIME) { $io->writeError(sprintf('<warning>Warning: This development build of Composer is over 60 days old. It is recommended to update it by running "%s self-update" to get the latest version.</warning>', $_SERVER['PHP_SELF'])); } if ($isNonAllowedRoot) { if ($commandName !== 'self-update' && $commandName !== 'selfupdate' && $commandName !== '_complete') { $io->writeError('<warning>Do not run Composer as root/super user! See https://getcomposer.org/root for details</warning>'); if ($io->isInteractive()) { if (!$io->askConfirmation('<info>Continue as root/super user</info> [<comment>yes</comment>]? ')) { return 1; } } } } // Check system temp folder for usability as it can cause weird runtime issues otherwise Silencer::call(static function () use ($io): void { $pid = function_exists('getmypid') ? getmypid() . '-' : ''; $tempfile = sys_get_temp_dir() . '/temp-' . $pid . bin2hex(random_bytes(5)); if (!(file_put_contents($tempfile, __FILE__) && (file_get_contents($tempfile) === __FILE__) && unlink($tempfile) && !file_exists($tempfile))) { $io->writeError(sprintf('<error>PHP temp directory (%s) does not exist or is not writable to Composer. Set sys_temp_dir in your php.ini</error>', sys_get_temp_dir())); } }); // add non-standard scripts as own commands $file = Factory::getComposerFile(); if (is_file($file) && Filesystem::isReadable($file) && is_array($composer = json_decode(file_get_contents($file), true))) { if (isset($composer['scripts']) && is_array($composer['scripts'])) { foreach ($composer['scripts'] as $script => $dummy) { if (!defined('Composer\Script\ScriptEvents::'.str_replace('-', '_', strtoupper($script)))) { if ($this->has($script)) { $io->writeError('<warning>A script named '.$script.' would override a Composer command and has been skipped</warning>'); } else { $description = null; if (isset($composer['scripts-descriptions'][$script])) { $description = $composer['scripts-descriptions'][$script]; } $aliases = $composer['scripts-aliases'][$script] ?? []; //if the command is not an array of commands, and points to a valid Command subclass, import its details directly if (is_string($dummy) && class_exists($dummy) && is_subclass_of($dummy, SymfonyCommand::class)) { $cmd = new $dummy($script); //makes sure the command is find()'able by the name defined in composer.json, and the name isn't overridden in its configure() if ($cmd->getName() !== '' && $cmd->getName() !== null && $cmd->getName() !== $script) { $io->writeError('<warning>The script named '.$script.' in composer.json has a mismatched name in its class definition. For consistency, either use the same name, or do not define one inside the class.</warning>'); $cmd->setName($script); //override it with the defined script name } if ($cmd->getDescription() === '' && is_string($description)) { $cmd->setDescription($description); } } else { //fallback to usual aliasing behavior $cmd = new Command\ScriptAliasCommand($script, $description, $aliases); } // Compatibility layer for symfony/console <7.4 // @phpstan-ignore method.notFound, function.alreadyNarrowedType method_exists($this, 'addCommand') ? $this->addCommand($cmd) : $this->add($cmd); } } } } } } try { if ($input->hasParameterOption('--profile')) { $startTime = microtime(true); $this->io->enableDebugging($startTime); } $result = parent::doRun($input, $output); if (true === $input->hasParameterOption(['--version', '-V'], true)) { $io->writeError(sprintf('<info>PHP</info> version <comment>%s</comment> (%s)', \PHP_VERSION, \PHP_BINARY)); $io->writeError('Run the "diagnose" command to get more detailed diagnostics output.'); } // chdir back to $oldWorkingDir if set if (isset($oldWorkingDir) && '' !== $oldWorkingDir) { Silencer::call('chdir', $oldWorkingDir); } if (isset($startTime)) { $io->writeError('<info>Memory usage: '.round(memory_get_usage() / 1024 / 1024, 2).'MiB (peak: '.round(memory_get_peak_usage() / 1024 / 1024, 2).'MiB), time: '.round(microtime(true) - $startTime, 2).'s</info>'); } return $result; } catch (ScriptExecutionException $e) { if ($this->getDisablePluginsByDefault() && $this->isRunningAsRoot() && !$this->io->isInteractive()) { $io->writeError('<error>Plugins have been disabled automatically as you are running as root, this may be the cause of the script failure.</error>', true, IOInterface::QUIET); $io->writeError('<error>See also https://getcomposer.org/root</error>', true, IOInterface::QUIET); } return $e->getCode(); } catch (\Throwable $e) { $ghe = new GithubActionError($this->io); $ghe->emit($e->getMessage()); $this->hintCommonErrors($e, $output); // symfony/console <6.4 does not handle \Error subtypes so we have to renderThrowable ourselves // instead of rethrowing those for consumption by the parent class // can be removed when Composer supports PHP 8.1+ if (!method_exists($this, 'setCatchErrors') && !$e instanceof \Exception) { if ($output instanceof ConsoleOutputInterface) { $this->renderThrowable($e, $output->getErrorOutput()); } else { $this->renderThrowable($e, $output); } return max(1, $e->getCode()); } // override TransportException's code for the purpose of parent::run() using it as process exit code // as http error codes are all beyond the 255 range of permitted exit codes if ($e instanceof TransportException) { $reflProp = new \ReflectionProperty($e, 'code'); (\PHP_VERSION_ID < 80100) and $reflProp->setAccessible(true); $reflProp->setValue($e, Installer::ERROR_TRANSPORT_EXCEPTION); } throw $e; } finally { restore_error_handler(); } } /** * @throws RuntimeException */ private function getNewWorkingDir(InputInterface $input): ?string { /** @var string|null $workingDir */ $workingDir = $input->getParameterOption(['--working-dir', '-d'], null, true); if (null !== $workingDir && !is_dir($workingDir)) { throw new RuntimeException('Invalid working directory specified, '.$workingDir.' does not exist.'); } return $workingDir; } private function hintCommonErrors(\Throwable $exception, OutputInterface $output): void { $io = $this->getIO(); if ((get_class($exception) === LogicException::class || $exception instanceof \Error) && $output->getVerbosity() < OutputInterface::VERBOSITY_VERBOSE) { $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE); } Silencer::suppress(); try { $composer = $this->getComposer(false, true); if (null !== $composer && function_exists('disk_free_space')) { $config = $composer->getConfig(); $minSpaceFree = 100 * 1024 * 1024; if ((($df = disk_free_space($dir = $config->get('home'))) !== false && $df < $minSpaceFree) || (($df = disk_free_space($dir = $config->get('vendor-dir'))) !== false && $df < $minSpaceFree) || (($df = disk_free_space($dir = sys_get_temp_dir())) !== false && $df < $minSpaceFree) ) { $io->writeError('<error>The disk hosting '.$dir.' has less than 100MiB of free space, this may be the cause of the following exception</error>', true, IOInterface::QUIET); } } } catch (\Exception $e) { } Silencer::restore(); if ($exception instanceof TransportException && str_contains($exception->getMessage(), 'Unable to use a proxy')) { $io->writeError('<error>The following exception indicates your proxy is misconfigured</error>', true, IOInterface::QUIET); $io->writeError('<error>Check https://getcomposer.org/doc/faqs/how-to-use-composer-behind-a-proxy.md for details</error>', true, IOInterface::QUIET); } if (Platform::isWindows() && $exception instanceof TransportException && str_contains($exception->getMessage(), 'unable to get local issuer certificate')) { $avastDetect = glob('C:\Program Files\Avast*'); if (is_array($avastDetect) && count($avastDetect) !== 0) { $io->writeError('<error>The following exception indicates a possible issue with the Avast Firewall</error>', true, IOInterface::QUIET); $io->writeError('<error>Check https://getcomposer.org/local-issuer for details</error>', true, IOInterface::QUIET); } else { $io->writeError('<error>The following exception indicates a possible issue with a Firewall/Antivirus</error>', true, IOInterface::QUIET); $io->writeError('<error>Check https://getcomposer.org/local-issuer for details</error>', true, IOInterface::QUIET); } } if (Platform::isWindows() && false !== strpos($exception->getMessage(), 'The system cannot find the path specified')) { $io->writeError('<error>The following exception may be caused by a stale entry in your cmd.exe AutoRun</error>', true, IOInterface::QUIET); $io->writeError('<error>Check https://getcomposer.org/doc/articles/troubleshooting.md#-the-system-cannot-find-the-path-specified-windows- for details</error>', true, IOInterface::QUIET); } if (false !== strpos($exception->getMessage(), 'fork failed - Cannot allocate memory')) { $io->writeError('<error>The following exception is caused by a lack of memory or swap, or not having swap configured</error>', true, IOInterface::QUIET); $io->writeError('<error>Check https://getcomposer.org/doc/articles/troubleshooting.md#proc-open-fork-failed-errors for details</error>', true, IOInterface::QUIET); } if ($exception instanceof ProcessTimedOutException) { $io->writeError('<error>The following exception is caused by a process timeout</error>', true, IOInterface::QUIET); $io->writeError('<error>Check https://getcomposer.org/doc/06-config.md#process-timeout for details</error>', true, IOInterface::QUIET); } if ($this->getDisablePluginsByDefault() && $this->isRunningAsRoot() && !$this->io->isInteractive()) { $io->writeError('<error>Plugins have been disabled automatically as you are running as root, this may be the cause of the following exception. See also https://getcomposer.org/root</error>', true, IOInterface::QUIET); } elseif ($exception instanceof CommandNotFoundException && $this->getDisablePluginsByDefault()) { $io->writeError('<error>Plugins have been disabled, which may be why some commands are missing, unless you made a typo</error>', true, IOInterface::QUIET); } $hints = HttpDownloader::getExceptionHints($exception); if (null !== $hints && count($hints) > 0) { foreach ($hints as $hint) { $io->writeError($hint, true, IOInterface::QUIET); } } } /** * @throws JsonValidationException * @throws \InvalidArgumentException * @return ?Composer If $required is true then the return value is guaranteed */ public function getComposer(bool $required = true, ?bool $disablePlugins = null, ?bool $disableScripts = null): ?Composer { if (null === $disablePlugins) { $disablePlugins = $this->disablePluginsByDefault; } if (null === $disableScripts) { $disableScripts = $this->disableScriptsByDefault; } if (null === $this->composer) { try { $this->composer = Factory::create(Platform::isInputCompletionProcess() ? new NullIO() : $this->io, null, $disablePlugins, $disableScripts); } catch (\InvalidArgumentException $e) { if ($required) { $this->io->writeError($e->getMessage()); if ($this->areExceptionsCaught()) { exit(1); } throw $e; } } catch (JsonValidationException $e) { if ($required) { throw $e; } } catch (RuntimeException $e) { if ($required) { throw $e; } } } return $this->composer; } /** * Removes the cached composer instance */ public function resetComposer(): void { $this->composer = null; if (method_exists($this->getIO(), 'resetAuthentications')) { $this->getIO()->resetAuthentications(); } } public function getIO(): IOInterface { return $this->io; } public function getHelp(): string { return self::$logo . parent::getHelp(); } /** * Initializes all the composer commands. * @return SymfonyCommand[] */ protected function getDefaultCommands(): array { return array_merge(parent::getDefaultCommands(), [ new Command\AboutCommand(), new Command\ConfigCommand(), new Command\DependsCommand(), new Command\ProhibitsCommand(), new Command\InitCommand(), new Command\InstallCommand(), new Command\CreateProjectCommand(), new Command\UpdateCommand(), new Command\SearchCommand(), new Command\ValidateCommand(), new Command\AuditCommand(), new Command\ShowCommand(), new Command\SuggestsCommand(), new Command\RequireCommand(), new Command\DumpAutoloadCommand(), new Command\StatusCommand(), new Command\ArchiveCommand(), new Command\DiagnoseCommand(), new Command\RunScriptCommand(), new Command\LicensesCommand(), new Command\GlobalCommand(), new Command\ClearCacheCommand(), new Command\RemoveCommand(), new Command\HomeCommand(), new Command\ExecCommand(), new Command\OutdatedCommand(), new Command\CheckPlatformReqsCommand(), new Command\FundCommand(), new Command\ReinstallCommand(), new Command\BumpCommand(), new Command\RepositoryCommand(), new Command\SelfUpdateCommand(), ]); } /** * This ensures we can find the correct command name even if a global input option is present before it * * e.g. "composer -d foo bar" should detect bar as the command name, and not foo */ private function getCommandNameBeforeBinding(InputInterface $input): ?string { $input = clone $input; try { // Makes ArgvInput::getFirstArgument() able to distinguish an option from an argument. $input->bind($this->getDefinition()); } catch (ExceptionInterface $e) { // Errors must be ignored, full binding/validation happens later when the command is known. } return $input->getFirstArgument(); } public function getLongVersion(): string { $branchAliasString = ''; if (Composer::BRANCH_ALIAS_VERSION && Composer::BRANCH_ALIAS_VERSION !== '@package_branch_alias_version'.'@') { $branchAliasString = sprintf(' (%s)', Composer::BRANCH_ALIAS_VERSION); } return sprintf( '<info>%s</info> version <comment>%s%s</comment> %s', $this->getName(),
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
true
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Console/GithubActionError.php
src/Composer/Console/GithubActionError.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\Console; use Composer\IO\IOInterface; use Composer\Util\Platform; final class GithubActionError { /** * @var IOInterface */ protected $io; public function __construct(IOInterface $io) { $this->io = $io; } public function emit(string $message, ?string $file = null, ?int $line = null): void { if (Platform::getEnv('GITHUB_ACTIONS') && !Platform::getEnv('COMPOSER_TESTS_ARE_RUNNING')) { $message = $this->escapeData($message); if ($file && $line) { $file = $this->escapeProperty($file); $this->io->write("::error file=". $file .",line=". $line ."::". $message); } elseif ($file) { $file = $this->escapeProperty($file); $this->io->write("::error file=". $file ."::". $message); } else { $this->io->write("::error ::". $message); } } } private function escapeData(string $data): string { // see https://github.com/actions/toolkit/blob/4f7fb6513a355689f69f0849edeb369a4dc81729/packages/core/src/command.ts#L80-L85 $data = str_replace("%", '%25', $data); $data = str_replace("\r", '%0D', $data); $data = str_replace("\n", '%0A', $data); return $data; } private function escapeProperty(string $property): string { // see https://github.com/actions/toolkit/blob/4f7fb6513a355689f69f0849edeb369a4dc81729/packages/core/src/command.ts#L87-L94 $property = str_replace("%", '%25', $property); $property = str_replace("\r", '%0D', $property); $property = str_replace("\n", '%0A', $property); $property = str_replace(":", '%3A', $property); $property = str_replace(",", '%2C', $property); return $property; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Console/Input/InputArgument.php
src/Composer/Console/Input/InputArgument.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\Console\Input; use Symfony\Component\Console\Completion\CompletionInput; use Symfony\Component\Console\Completion\CompletionSuggestions; use Symfony\Component\Console\Completion\Suggestion; use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Exception\LogicException; use Symfony\Component\Console\Input\InputArgument as BaseInputArgument; /** * Backport suggested values definition from symfony/console 6.1+ * * @author Jérôme Tamarelle <jerome@tamarelle.net> * * @internal * * TODO symfony/console:6.1 drop when PHP 8.1 / symfony 6.1+ can be required */ class InputArgument extends BaseInputArgument { /** * @var list<string>|\Closure(CompletionInput,CompletionSuggestions):list<string|Suggestion> */ private $suggestedValues; /** * @param string $name The argument name * @param int|null $mode The argument mode: self::REQUIRED or self::OPTIONAL * @param string $description A description text * @param string|bool|int|float|string[]|null $default The default value (for self::OPTIONAL mode only) * @param list<string>|\Closure(CompletionInput,CompletionSuggestions):list<string|Suggestion> $suggestedValues The values used for input completion * * @throws InvalidArgumentException When argument mode is not valid */ public function __construct(string $name, ?int $mode = null, string $description = '', $default = null, $suggestedValues = []) { parent::__construct($name, $mode, $description, $default); $this->suggestedValues = $suggestedValues; } /** * Adds suggestions to $suggestions for the current completion input. * * @see Command::complete() */ public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void { $values = $this->suggestedValues; if ($values instanceof \Closure && !\is_array($values = $values($input, $suggestions))) { // @phpstan-ignore function.impossibleType throw new LogicException(sprintf('Closure for option "%s" must return an array. Got "%s".', $this->getName(), get_debug_type($values))); } if ([] !== $values) { $suggestions->suggestValues($values); } } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Console/Input/InputOption.php
src/Composer/Console/Input/InputOption.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\Console\Input; use Symfony\Component\Console\Completion\CompletionInput; use Symfony\Component\Console\Completion\CompletionSuggestions; use Symfony\Component\Console\Completion\Suggestion; use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Exception\LogicException; use Symfony\Component\Console\Input\InputOption as BaseInputOption; /** * Backport suggested values definition from symfony/console 6.1+ * * @author Jérôme Tamarelle <jerome@tamarelle.net> * * @internal * * TODO symfony/console:6.1 drop when PHP 8.1 / symfony 6.1+ can be required */ class InputOption extends BaseInputOption { /** * @var list<string>|\Closure(CompletionInput,CompletionSuggestions):list<string|Suggestion> */ private $suggestedValues; /** * @param string|string[]|null $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts * @param int|null $mode The option mode: One of the VALUE_* constants * @param string|bool|int|float|string[]|null $default The default value (must be null for self::VALUE_NONE) * @param list<string>|\Closure(CompletionInput,CompletionSuggestions):list<string|Suggestion> $suggestedValues The values used for input completionnull for self::VALUE_NONE) * * @throws InvalidArgumentException If option mode is invalid or incompatible */ public function __construct(string $name, $shortcut = null, ?int $mode = null, string $description = '', $default = null, $suggestedValues = []) { parent::__construct($name, $shortcut, $mode, $description, $default); $this->suggestedValues = $suggestedValues; if ([] !== $suggestedValues && !$this->acceptValue()) { throw new LogicException('Cannot set suggested values if the option does not accept a value.'); } } /** * Adds suggestions to $suggestions for the current completion input. * * @see Command::complete() */ public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void { $values = $this->suggestedValues; if ($values instanceof \Closure && !\is_array($values = $values($input, $suggestions))) { // @phpstan-ignore function.impossibleType throw new LogicException(sprintf('Closure for argument "%s" must return an array. Got "%s".', $this->getName(), get_debug_type($values))); } if ([] !== $values) { $suggestions->suggestValues($values); } } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/IniHelper.php
src/Composer/Util/IniHelper.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\Util; use Composer\XdebugHandler\XdebugHandler; /** * Provides ini file location functions that work with and without a restart. * When the process has restarted it uses a tmp ini and stores the original * ini locations in an environment variable. * * @author John Stevenson <john-stevenson@blueyonder.co.uk> */ class IniHelper { /** * Returns an array of php.ini locations with at least one entry * * The equivalent of calling php_ini_loaded_file then php_ini_scanned_files. * The loaded ini location is the first entry and may be empty. * * @return string[] */ public static function getAll(): array { return XdebugHandler::getAllIniFiles(); } /** * Describes the location of the loaded php.ini file(s) */ public static function getMessage(): string { $paths = self::getAll(); if (empty($paths[0])) { array_shift($paths); } $ini = array_shift($paths); if (empty($ini)) { return 'A php.ini file does not exist. You will have to create one.'; } if (!empty($paths)) { return 'Your command-line PHP is using multiple ini files. Run `php --ini` to show them.'; } return 'The php.ini used by your command-line PHP is: '.$ini; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Svn.php
src/Composer/Util/Svn.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\Util; use Composer\Config; use Composer\IO\IOInterface; use Composer\Pcre\Preg; /** * @author Till Klampaeckel <till@php.net> * @author Jordi Boggiano <j.boggiano@seld.be> */ class Svn { private const MAX_QTY_AUTH_TRIES = 5; /** * @var ?array{username: string, password: string} */ protected $credentials; /** * @var bool */ protected $hasAuth; /** * @var IOInterface */ protected $io; /** * @var string */ protected $url; /** * @var bool */ protected $cacheCredentials = true; /** * @var ProcessExecutor */ protected $process; /** * @var int */ protected $qtyAuthTries = 0; /** * @var Config */ protected $config; /** * @var string|null */ private static $version; public function __construct(string $url, IOInterface $io, Config $config, ?ProcessExecutor $process = null) { $this->url = $url; $this->io = $io; $this->config = $config; $this->process = $process ?: new ProcessExecutor($io); } public static function cleanEnv(): void { // clean up env for OSX, see https://github.com/composer/composer/issues/2146#issuecomment-35478940 Platform::clearEnv('DYLD_LIBRARY_PATH'); } /** * Execute an SVN remote command and try to fix up the process with credentials * if necessary. * * @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 * @param bool $verbose Output all output to the user * * @throws \RuntimeException */ public function execute(array $command, string $url, ?string $cwd = null, ?string $path = null, bool $verbose = false): string { // Ensure we are allowed to use this URL by config $this->config->prohibitUrlByConfig($url, $this->io); return $this->executeWithAuthRetry($command, $cwd, $url, $path, $verbose); } /** * Execute an SVN local command and try to fix up the process with credentials * if necessary. * * @param non-empty-list<string> $command SVN command to run * @param string $path Path argument passed thru to the command * @param string $cwd Working directory * @param bool $verbose Output all output to the user * * @throws \RuntimeException */ public function executeLocal(array $command, string $path, ?string $cwd = null, bool $verbose = false): string { // A local command has no remote url return $this->executeWithAuthRetry($command, $cwd, '', $path, $verbose); } /** * @param non-empty-list<string> $svnCommand */ private function executeWithAuthRetry(array $svnCommand, ?string $cwd, string $url, ?string $path, bool $verbose): ?string { // Regenerate the command at each try, to use the newly user-provided credentials $command = $this->getCommand($svnCommand, $url, $path); $output = null; $io = $this->io; $handler = static function ($type, $buffer) use (&$output, $io, $verbose) { if ($type !== 'out') { return null; } if (strpos($buffer, 'Redirecting to URL ') === 0) { return null; } $output .= $buffer; if ($verbose) { $io->writeError($buffer, false); } }; $status = $this->process->execute($command, $handler, $cwd); if (0 === $status) { return $output; } $errorOutput = $this->process->getErrorOutput(); $fullOutput = trim(implode("\n", [$output, $errorOutput])); // the error is not auth-related if (false === stripos($fullOutput, 'Could not authenticate to server:') && false === stripos($fullOutput, 'authorization failed') && false === stripos($fullOutput, 'svn: E170001:') && false === stripos($fullOutput, 'svn: E215004:')) { throw new \RuntimeException($fullOutput); } if (!$this->hasAuth()) { $this->doAuthDance(); } // try to authenticate if maximum quantity of tries not reached if ($this->qtyAuthTries++ < self::MAX_QTY_AUTH_TRIES) { // restart the process return $this->executeWithAuthRetry($svnCommand, $cwd, $url, $path, $verbose); } throw new \RuntimeException( 'wrong credentials provided ('.$fullOutput.')' ); } public function setCacheCredentials(bool $cacheCredentials): void { $this->cacheCredentials = $cacheCredentials; } /** * Repositories requests credentials, let's put them in. * * @throws \RuntimeException */ protected function doAuthDance(): Svn { // cannot ask for credentials in non interactive mode if (!$this->io->isInteractive()) { throw new \RuntimeException( 'can not ask for authentication in non interactive mode' ); } $this->io->writeError("The Subversion server ({$this->url}) requested credentials:"); $this->hasAuth = true; $this->credentials = [ 'username' => (string) $this->io->ask("Username: ", ''), 'password' => (string) $this->io->askAndHideAnswer("Password: "), ]; $this->cacheCredentials = $this->io->askConfirmation("Should Subversion cache these credentials? (yes/no) "); return $this; } /** * A method to create the svn commands run. * * @param non-empty-list<string> $cmd Usually 'svn ls' or something like that. * @param string $url Repo URL. * @param string $path Target for a checkout * * @return non-empty-list<string> */ protected function getCommand(array $cmd, string $url, ?string $path = null): array { $cmd = array_merge( $cmd, ['--non-interactive'], $this->getCredentialArgs(), ['--', $url] ); if ($path !== null) { $cmd[] = $path; } return $cmd; } /** * Return the credential string for the svn command. * * Adds --no-auth-cache when credentials are present. * * @return list<string> */ protected function getCredentialArgs(): array { if (!$this->hasAuth()) { return []; } return array_merge( $this->getAuthCacheArgs(), ['--username', $this->getUsername(), '--password', $this->getPassword()] ); } /** * Get the password for the svn command. Can be empty. * * @throws \LogicException */ protected function getPassword(): string { if ($this->credentials === null) { throw new \LogicException("No svn auth detected."); } return $this->credentials['password']; } /** * Get the username for the svn command. * * @throws \LogicException */ protected function getUsername(): string { if ($this->credentials === null) { throw new \LogicException("No svn auth detected."); } return $this->credentials['username']; } /** * Detect Svn Auth. */ protected function hasAuth(): bool { if (null !== $this->hasAuth) { return $this->hasAuth; } if (false === $this->createAuthFromConfig()) { $this->createAuthFromUrl(); } return (bool) $this->hasAuth; } /** * Return the no-auth-cache switch. * * @return list<string> */ protected function getAuthCacheArgs(): array { return $this->cacheCredentials ? [] : ['--no-auth-cache']; } /** * Create the auth params from the configuration file. */ private function createAuthFromConfig(): bool { if (!$this->config->has('http-basic')) { return $this->hasAuth = false; } $authConfig = $this->config->get('http-basic'); $host = parse_url($this->url, PHP_URL_HOST); if (isset($authConfig[$host])) { $this->credentials = [ 'username' => $authConfig[$host]['username'], 'password' => $authConfig[$host]['password'], ]; return $this->hasAuth = true; } return $this->hasAuth = false; } /** * Create the auth params from the url */ private function createAuthFromUrl(): bool { $uri = parse_url($this->url); if (empty($uri['user'])) { return $this->hasAuth = false; } $this->credentials = [ 'username' => $uri['user'], 'password' => !empty($uri['pass']) ? $uri['pass'] : '', ]; return $this->hasAuth = true; } /** * Returns the version of the svn binary contained in PATH */ public function binaryVersion(): ?string { if (!self::$version) { if (0 === $this->process->execute(['svn', '--version'], $output)) { if (Preg::isMatch('{(\d+(?:\.\d+)+)}', $output, $match)) { self::$version = $match[1]; } } } return self::$version; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Filesystem.php
src/Composer/Util/Filesystem.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\Util; use Composer\Pcre\Preg; use ErrorException; use React\Promise\PromiseInterface; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use Symfony\Component\Filesystem\Exception\IOException; use Symfony\Component\Finder\Finder; /** * @author Jordi Boggiano <j.boggiano@seld.be> * @author Johannes M. Schmitt <schmittjoh@gmail.com> */ class Filesystem { /** @var ?ProcessExecutor */ private $processExecutor; public function __construct(?ProcessExecutor $executor = null) { $this->processExecutor = $executor; } /** * @return bool */ public function remove(string $file) { if (is_dir($file)) { return $this->removeDirectory($file); } if (file_exists($file)) { return $this->unlink($file); } return false; } /** * Checks if a directory is empty * * @return bool */ public function isDirEmpty(string $dir) { $finder = Finder::create() ->ignoreVCS(false) ->ignoreDotFiles(false) ->depth(0) ->in($dir); return \count($finder) === 0; } /** * @return void */ public function emptyDirectory(string $dir, bool $ensureDirectoryExists = true) { if (is_link($dir) && file_exists($dir)) { $this->unlink($dir); } if ($ensureDirectoryExists) { $this->ensureDirectoryExists($dir); } if (is_dir($dir)) { $finder = Finder::create() ->ignoreVCS(false) ->ignoreDotFiles(false) ->depth(0) ->in($dir); foreach ($finder as $path) { $this->remove((string) $path); } } } /** * Recursively remove a directory * * Uses the process component if proc_open is enabled on the PHP * installation. * * @throws \RuntimeException * @return bool */ public function removeDirectory(string $directory) { $edgeCaseResult = $this->removeEdgeCases($directory); if ($edgeCaseResult !== null) { return $edgeCaseResult; } if (Platform::isWindows()) { $cmd = ['rmdir', '/S', '/Q', Platform::realpath($directory)]; } else { $cmd = ['rm', '-rf', $directory]; } $result = $this->getProcess()->execute($cmd, $output) === 0; // clear stat cache because external processes aren't tracked by the php stat cache clearstatcache(); if ($result && !is_dir($directory)) { return true; } return $this->removeDirectoryPhp($directory); } /** * Recursively remove a directory asynchronously * * Uses the process component if proc_open is enabled on the PHP * installation. * * @throws \RuntimeException * @return PromiseInterface * @phpstan-return PromiseInterface<bool> */ public function removeDirectoryAsync(string $directory) { $edgeCaseResult = $this->removeEdgeCases($directory); if ($edgeCaseResult !== null) { return \React\Promise\resolve($edgeCaseResult); } if (Platform::isWindows()) { $cmd = ['rmdir', '/S', '/Q', Platform::realpath($directory)]; } else { $cmd = ['rm', '-rf', $directory]; } $promise = $this->getProcess()->executeAsync($cmd); return $promise->then(function ($process) use ($directory) { // clear stat cache because external processes aren't tracked by the php stat cache clearstatcache(); if ($process->isSuccessful()) { if (!is_dir($directory)) { return \React\Promise\resolve(true); } } return \React\Promise\resolve($this->removeDirectoryPhp($directory)); }); } /** * @return bool|null Returns null, when no edge case was hit. Otherwise a bool whether removal was successful */ private function removeEdgeCases(string $directory, bool $fallbackToPhp = true): ?bool { if ($this->isSymlinkedDirectory($directory)) { return $this->unlinkSymlinkedDirectory($directory); } if ($this->isJunction($directory)) { return $this->removeJunction($directory); } if (is_link($directory)) { return unlink($directory); } if (!is_dir($directory) || !file_exists($directory)) { return true; } if (Preg::isMatch('{^(?:[a-z]:)?[/\\\\]+$}i', $directory)) { throw new \RuntimeException('Aborting an attempted deletion of '.$directory.', this was probably not intended, if it is a real use case please report it.'); } if (!\function_exists('proc_open') && $fallbackToPhp) { return $this->removeDirectoryPhp($directory); } return null; } /** * Recursively delete directory using PHP iterators. * * Uses a CHILD_FIRST RecursiveIteratorIterator to sort files * before directories, creating a single non-recursive loop * to delete files/directories in the correct order. * * @return bool */ public function removeDirectoryPhp(string $directory) { $edgeCaseResult = $this->removeEdgeCases($directory, false); if ($edgeCaseResult !== null) { return $edgeCaseResult; } try { $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS); } catch (\UnexpectedValueException $e) { // re-try once after clearing the stat cache if it failed as it // sometimes fails without apparent reason, see https://github.com/composer/composer/issues/4009 clearstatcache(); usleep(100000); if (!is_dir($directory)) { return true; } $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS); } $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST); foreach ($ri as $file) { if ($file->isDir()) { $this->rmdir($file->getPathname()); } else { $this->unlink($file->getPathname()); } } // release locks on the directory, see https://github.com/composer/composer/issues/9945 unset($ri, $it, $file); return $this->rmdir($directory); } /** * @return void */ public function ensureDirectoryExists(string $directory) { if (!is_dir($directory)) { if (file_exists($directory)) { throw new \RuntimeException( $directory.' exists and is not a directory.' ); } if (is_link($directory) && !@$this->unlinkImplementation($directory)) { throw new \RuntimeException('Could not delete symbolic link '.$directory.': '.(error_get_last()['message'] ?? '')); } if (!@mkdir($directory, 0777, true)) { $e = new \RuntimeException($directory.' does not exist and could not be created: '.(error_get_last()['message'] ?? '')); // in pathological cases with paths like path/to/broken-symlink/../foo is_dir will fail to detect path/to/foo // but normalizing the ../ away first makes it work so we attempt this just in case, and if it still fails we // report the initial error we had with the original path, and ignore the normalized path exception // see https://github.com/composer/composer/issues/11864 $normalized = $this->normalizePath($directory); if ($normalized !== $directory) { try { $this->ensureDirectoryExists($normalized); return; } catch (\Throwable $ignoredEx) { } } throw $e; } } } /** * Attempts to unlink a file and in case of failure retries after 350ms on windows * * @throws \RuntimeException * @return bool */ public function unlink(string $path) { $unlinked = @$this->unlinkImplementation($path); if (!$unlinked) { // retry after a bit on windows since it tends to be touchy with mass removals if (Platform::isWindows()) { usleep(350000); $unlinked = @$this->unlinkImplementation($path); } if (!$unlinked) { $error = error_get_last(); $message = 'Could not delete '.$path.': ' . ($error['message'] ?? ''); if (Platform::isWindows()) { $message .= "\nThis can be due to an antivirus or the Windows Search Indexer locking the file while they are analyzed"; } throw new \RuntimeException($message); } } return true; } /** * Attempts to rmdir a file and in case of failure retries after 350ms on windows * * @throws \RuntimeException * @return bool */ public function rmdir(string $path) { $deleted = @rmdir($path); if (!$deleted) { // retry after a bit on windows since it tends to be touchy with mass removals if (Platform::isWindows()) { usleep(350000); $deleted = @rmdir($path); } if (!$deleted) { $error = error_get_last(); $message = 'Could not delete '.$path.': ' . ($error['message'] ?? ''); if (Platform::isWindows()) { $message .= "\nThis can be due to an antivirus or the Windows Search Indexer locking the file while they are analyzed"; } throw new \RuntimeException($message); } } return true; } /** * Copy then delete is a non-atomic version of {@link rename}. * * Some systems can't rename and also don't have proc_open, * which requires this solution. * * @return void */ public function copyThenRemove(string $source, string $target) { $this->copy($source, $target); if (!is_dir($source)) { $this->unlink($source); return; } $this->removeDirectoryPhp($source); } /** * Copies a file or directory from $source to $target. * * @return bool */ public function copy(string $source, string $target) { // refs https://github.com/composer/composer/issues/11864 $target = $this->normalizePath($target); if (!is_dir($source)) { try { return copy($source, $target); } catch (ErrorException $e) { // if copy fails we attempt to copy it manually as this can help bypass issues with VirtualBox shared folders // see https://github.com/composer/composer/issues/12057 if (str_contains($e->getMessage(), 'Bad address')) { $sourceHandle = fopen($source, 'r'); $targetHandle = fopen($target, 'w'); if (false === $sourceHandle || false === $targetHandle) { throw $e; } while (!feof($sourceHandle)) { if (false === fwrite($targetHandle, (string) fread($sourceHandle, 1024 * 1024))) { throw $e; } } fclose($sourceHandle); fclose($targetHandle); return true; } throw $e; } } $it = new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS); $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST); $this->ensureDirectoryExists($target); $result = true; foreach ($ri as $file) { $targetPath = $target . DIRECTORY_SEPARATOR . $ri->getSubPathname(); if ($file->isDir()) { $this->ensureDirectoryExists($targetPath); } else { $result = $result && copy($file->getPathname(), $targetPath); } } return $result; } /** * @return void */ public function rename(string $source, string $target) { if (true === @rename($source, $target)) { return; } if (!\function_exists('proc_open')) { $this->copyThenRemove($source, $target); return; } if (Platform::isWindows()) { // Try to copy & delete - this is a workaround for random "Access denied" errors. $result = $this->getProcess()->execute(['xcopy', $source, $target, '/E', '/I', '/Q', '/Y'], $output); // clear stat cache because external processes aren't tracked by the php stat cache clearstatcache(); if (0 === $result) { $this->remove($source); return; } } else { // We do not use PHP's "rename" function here since it does not support // the case where $source, and $target are located on different partitions. $result = $this->getProcess()->execute(['mv', $source, $target], $output); // clear stat cache because external processes aren't tracked by the php stat cache clearstatcache(); if (0 === $result) { return; } } $this->copyThenRemove($source, $target); } /** * Returns the shortest path from $from to $to * * @param bool $directories if true, the source/target are considered to be directories * @param bool $preferRelative if true, relative paths will be preferred even if longer * @throws \InvalidArgumentException * @return string */ public function findShortestPath(string $from, string $to, bool $directories = false, bool $preferRelative = false) { if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) { throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to)); } $from = $this->normalizePath($from); $to = $this->normalizePath($to); if ($directories) { $from = rtrim($from, '/') . '/dummy_file'; } if (\dirname($from) === \dirname($to)) { return './'.basename($to); } $commonPath = $to; while (strpos($from.'/', $commonPath.'/') !== 0 && '/' !== $commonPath && !Preg::isMatch('{^[A-Z]:/?$}i', $commonPath)) { $commonPath = strtr(\dirname($commonPath), '\\', '/'); } // no commonality at all if (0 !== strpos($from, $commonPath)) { return $to; } $commonPath = rtrim($commonPath, '/') . '/'; $sourcePathDepth = substr_count((string) substr($from, \strlen($commonPath)), '/'); $commonPathCode = str_repeat('../', $sourcePathDepth); // allow top level /foo & /bar dirs to be addressed relatively as this is common in Docker setups if (!$preferRelative && '/' === $commonPath && $sourcePathDepth > 1) { return $to; } $result = $commonPathCode . substr($to, \strlen($commonPath)); if (\strlen($result) === 0) { return './'; } return $result; } /** * Returns PHP code that, when executed in $from, will return the path to $to * * @param bool $directories if true, the source/target are considered to be directories * @param bool $preferRelative if true, relative paths will be preferred even if longer * @throws \InvalidArgumentException * @return string */ public function findShortestPathCode(string $from, string $to, bool $directories = false, bool $staticCode = false, bool $preferRelative = false) { if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) { throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to)); } $from = $this->normalizePath($from); $to = $this->normalizePath($to); if ($from === $to) { return $directories ? '__DIR__' : '__FILE__'; } $commonPath = $to; while (strpos($from.'/', $commonPath.'/') !== 0 && '/' !== $commonPath && !Preg::isMatch('{^[A-Z]:/?$}i', $commonPath) && '.' !== $commonPath) { $commonPath = strtr(\dirname($commonPath), '\\', '/'); } // no commonality at all if (0 !== strpos($from, $commonPath) || '.' === $commonPath) { return var_export($to, true); } $commonPath = rtrim($commonPath, '/') . '/'; if (str_starts_with($to, $from.'/')) { return '__DIR__ . '.var_export((string) substr($to, \strlen($from)), true); } $sourcePathDepth = substr_count((string) substr($from, \strlen($commonPath)), '/') + (int) $directories; // allow top level /foo & /bar dirs to be addressed relatively as this is common in Docker setups if (!$preferRelative && '/' === $commonPath && $sourcePathDepth > 1) { return var_export($to, true); } if ($staticCode) { $commonPathCode = "__DIR__ . '".str_repeat('/..', $sourcePathDepth)."'"; } else { $commonPathCode = str_repeat('dirname(', $sourcePathDepth).'__DIR__'.str_repeat(')', $sourcePathDepth); } $relTarget = (string) substr($to, \strlen($commonPath)); return $commonPathCode . (\strlen($relTarget) > 0 ? '.' . var_export('/' . $relTarget, true) : ''); } /** * Checks if the given path is absolute * * @return bool */ public function isAbsolutePath(string $path) { return strpos($path, '/') === 0 || substr($path, 1, 1) === ':' || strpos($path, '\\\\') === 0; } /** * Returns size of a file or directory specified by path. If a directory is * given, its size will be computed recursively. * * @param string $path Path to the file or directory * @throws \RuntimeException * @return int */ public function size(string $path) { if (!file_exists($path)) { throw new \RuntimeException("$path does not exist."); } if (is_dir($path)) { return $this->directorySize($path); } return (int) filesize($path); } /** * Normalize a path. This replaces backslashes with slashes, removes ending * slash and collapses redundant separators and up-level references. * * @param string $path Path to the file or directory * @return string */ public function normalizePath(string $path) { $parts = []; $path = strtr($path, '\\', '/'); $prefix = ''; $absolute = ''; // extract windows UNC paths e.g. \\foo\bar if (strpos($path, '//') === 0 && \strlen($path) > 2) { $absolute = '//'; $path = substr($path, 2); } // extract a prefix being a protocol://, protocol:, protocol://drive: or simply drive: if (Preg::isMatchStrictGroups('{^( [0-9a-z]{2,}+: (?: // (?: [a-z]: )? )? | [a-z]: )}ix', $path, $match)) { $prefix = $match[1]; $path = substr($path, \strlen($prefix)); } if (strpos($path, '/') === 0) { $absolute = '/'; $path = substr($path, 1); } $up = false; foreach (explode('/', $path) as $chunk) { if ('..' === $chunk && (\strlen($absolute) > 0 || $up)) { array_pop($parts); $up = !(\count($parts) === 0 || '..' === end($parts)); } elseif ('.' !== $chunk && '' !== $chunk) { $parts[] = $chunk; $up = '..' !== $chunk; } } // ensure c: is normalized to C: $prefix = Preg::replaceCallback('{(^|://)[a-z]:$}i', static function (array $m) { return strtoupper($m[0]); }, $prefix); return $prefix.$absolute.implode('/', $parts); } /** * Remove trailing slashes if present to avoid issues with symlinks * * And other possible unforeseen disasters, see https://github.com/composer/composer/pull/9422 * * @return string */ public static function trimTrailingSlash(string $path) { if (!Preg::isMatch('{^[/\\\\]+$}', $path)) { $path = rtrim($path, '/\\'); } return $path; } /** * Return if the given path is local * * @return bool */ public static function isLocalPath(string $path) { // on windows, \\foo indicates network paths so we exclude those from local paths, however it is unsafe // on linux as file:////foo (which would be a network path \\foo on windows) will resolve to /foo which could be a local path if (Platform::isWindows()) { return Preg::isMatch('{^(file://(?!//)|/(?!/)|/?[a-z]:[\\\\/]|\.\.[\\\\/]|[a-z0-9_.-]+[\\\\/])}i', $path); } return Preg::isMatch('{^(file://|/|/?[a-z]:[\\\\/]|\.\.[\\\\/]|[a-z0-9_.-]+[\\\\/])}i', $path); } /** * @return string */ public static function getPlatformPath(string $path) { if (Platform::isWindows()) { $path = Preg::replace('{^(?:file:///([a-z]):?/)}i', 'file://$1:/', $path); } return Preg::replace('{^file://}i', '', $path); } /** * Cross-platform safe version of is_readable() * * This will also check for readability by reading the file as is_readable can not be trusted on network-mounts * and \\wsl$ paths. See https://github.com/composer/composer/issues/8231 and https://bugs.php.net/bug.php?id=68926 * * @return bool */ public static function isReadable(string $path) { if (is_readable($path)) { return true; } if (is_file($path)) { return false !== Silencer::call('file_get_contents', $path, false, null, 0, 1); } if (is_dir($path)) { return false !== Silencer::call('opendir', $path); } // assume false otherwise return false; } /** * @return int */ protected function directorySize(string $directory) { $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS); $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST); $size = 0; foreach ($ri as $file) { if ($file->isFile()) { $size += $file->getSize(); } } return $size; } /** * @return ProcessExecutor */ protected function getProcess() { if (null === $this->processExecutor) { $this->processExecutor = new ProcessExecutor(); } return $this->processExecutor; } /** * delete symbolic link implementation (commonly known as "unlink()") * * symbolic links on windows which link to directories need rmdir instead of unlink */ private function unlinkImplementation(string $path): bool { if (Platform::isWindows() && is_dir($path) && is_link($path)) { return rmdir($path); } return unlink($path); } /** * Creates a relative symlink from $link to $target * * @param string $target The path of the binary file to be symlinked * @param string $link The path where the symlink should be created * @return bool */ public function relativeSymlink(string $target, string $link) { if (!function_exists('symlink')) { return false; } $cwd = Platform::getCwd(); $relativePath = $this->findShortestPath($link, $target); chdir(\dirname($link)); $result = @symlink($relativePath, $link); chdir($cwd); return $result; } /** * return true if that directory is a symlink. * * @return bool */ public function isSymlinkedDirectory(string $directory) { if (!is_dir($directory)) { return false; } $resolved = $this->resolveSymlinkedDirectorySymlink($directory); return is_link($resolved); } private function unlinkSymlinkedDirectory(string $directory): bool { $resolved = $this->resolveSymlinkedDirectorySymlink($directory); return $this->unlink($resolved); } /** * resolve pathname to symbolic link of a directory * * @param string $pathname directory path to resolve * * @return string resolved path to symbolic link or original pathname (unresolved) */ private function resolveSymlinkedDirectorySymlink(string $pathname): string { if (!is_dir($pathname)) { return $pathname; } $resolved = rtrim($pathname, '/'); if (0 === \strlen($resolved)) { return $pathname; } return $resolved; } /** * Creates an NTFS junction. * * @return void */ public function junction(string $target, string $junction) { if (!Platform::isWindows()) { throw new \LogicException(sprintf('Function %s is not available on non-Windows platform', __CLASS__)); } if (!is_dir($target)) { throw new IOException(sprintf('Cannot junction to "%s" as it is not a directory.', $target), 0, null, $target); } // Removing any previously junction to ensure clean execution. if (!is_dir($junction) || $this->isJunction($junction)) { @rmdir($junction); } $cmd = ['mklink', '/J', str_replace('/', DIRECTORY_SEPARATOR, $junction), Platform::realpath($target)]; if ($this->getProcess()->execute($cmd, $output) !== 0) { throw new IOException(sprintf('Failed to create junction to "%s" at "%s".', $target, $junction), 0, null, $target); } clearstatcache(true, $junction); } /** * Returns whether the target directory is a Windows NTFS Junction. * * We test if the path is a directory and not an ordinary link, then check * that the mode value returned from lstat (which gives the status of the * link itself) is not a directory, by replicating the POSIX S_ISDIR test. * * This logic works because PHP does not set the mode value for a junction, * since there is no universal file type flag for it. Unfortunately an * uninitialized variable in PHP prior to 7.2.16 and 7.3.3 may cause a * random value to be returned. See https://bugs.php.net/bug.php?id=77552 * * If this random value passes the S_ISDIR test, then a junction will not be * detected and a recursive delete operation could lead to loss of data in * the target directory. Note that Windows rmdir can handle this situation * and will only delete the junction (from Windows 7 onwards). * * @param string $junction Path to check. * @return bool */ public function isJunction(string $junction) { if (!Platform::isWindows()) { return false; } // Important to clear all caches first clearstatcache(true, $junction); if (!is_dir($junction) || is_link($junction)) { return false; } $stat = lstat($junction); // S_ISDIR test (S_IFDIR is 0x4000, S_IFMT is 0xF000 bitmask) return is_array($stat) ? 0x4000 !== ($stat['mode'] & 0xF000) : false; } /** * Removes a Windows NTFS junction. * * @return bool */ public function removeJunction(string $junction) { if (!Platform::isWindows()) { return false; } $junction = rtrim(str_replace('/', DIRECTORY_SEPARATOR, $junction), DIRECTORY_SEPARATOR); if (!$this->isJunction($junction)) { throw new IOException(sprintf('%s is not a junction and thus cannot be removed as one', $junction)); } return $this->rmdir($junction); } /** * @return int|false */ public function filePutContentsIfModified(string $path, string $content) { $currentContent = Silencer::call('file_get_contents', $path); if (false === $currentContent || $currentContent !== $content) { return file_put_contents($path, $content); } return 0; } /** * Copy file using stream_copy_to_stream to work around https://bugs.php.net/bug.php?id=6463 */ public function safeCopy(string $source, string $target): void { if (!file_exists($target) || !file_exists($source) || !$this->filesAreEqual($source, $target)) { $sourceHandle = fopen($source, 'r'); assert($sourceHandle !== false, 'Could not open "'.$source.'" for reading.'); $targetHandle = fopen($target, 'w+'); assert($targetHandle !== false, 'Could not open "'.$target.'" for writing.'); stream_copy_to_stream($sourceHandle, $targetHandle); fclose($sourceHandle); fclose($targetHandle); touch($target, (int) filemtime($source), (int) fileatime($source)); } } /** * compare 2 files * https://stackoverflow.com/questions/3060125/can-i-use-file-get-contents-to-compare-two-files */ private function filesAreEqual(string $a, string $b): bool { // Check if filesize is different if (filesize($a) !== filesize($b)) { return false; } // Check if content is different $aHandle = fopen($a, 'rb'); assert($aHandle !== false, 'Could not open "'.$a.'" for reading.'); $bHandle = fopen($b, 'rb'); assert($bHandle !== false, 'Could not open "'.$b.'" for reading.'); $result = true; while (!feof($aHandle)) { if (fread($aHandle, 8192) !== fread($bHandle, 8192)) { $result = false; break; } } fclose($aHandle); fclose($bHandle); return $result; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Platform.php
src/Composer/Util/Platform.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\Util; use Composer\Pcre\Preg; /** * Platform helper for uniform platform-specific tests. * * @author Niels Keurentjes <niels.keurentjes@omines.com> */ class Platform { /** @var ?bool */ private static $isVirtualBoxGuest = null; /** @var ?bool */ private static $isWindowsSubsystemForLinux = null; /** @var ?bool */ private static $isDocker = null; /** * getcwd() equivalent which always returns a string * * @throws \RuntimeException */ public static function getCwd(bool $allowEmpty = false): string { $cwd = getcwd(); // fallback to realpath('') just in case this works but odds are it would break as well if we are in a case where getcwd fails if (false === $cwd) { $cwd = realpath(''); } // crappy state, assume '' and hopefully relative paths allow things to continue if (false === $cwd) { if ($allowEmpty) { return ''; } throw new \RuntimeException('Could not determine the current working directory'); } return $cwd; } /** * Infallible realpath version that falls back on the given $path if realpath is not working */ public static function realpath(string $path): string { $realPath = realpath($path); if ($realPath === false) { return $path; } return $realPath; } /** * getenv() equivalent but reads from the runtime global variables first * * @param non-empty-string $name * * @return string|false */ public static function getEnv(string $name) { if (array_key_exists($name, $_SERVER)) { return (string) $_SERVER[$name]; } if (array_key_exists($name, $_ENV)) { return (string) $_ENV[$name]; } return getenv($name); } /** * putenv() equivalent but updates the runtime global variables too */ public static function putEnv(string $name, string $value): void { putenv($name . '=' . $value); $_SERVER[$name] = $_ENV[$name] = $value; } /** * putenv('X') equivalent but updates the runtime global variables too */ public static function clearEnv(string $name): void { putenv($name); unset($_SERVER[$name], $_ENV[$name]); } /** * Parses tildes and environment variables in paths. */ public static function expandPath(string $path): string { if (Preg::isMatch('#^~[\\/]#', $path)) { return self::getUserDirectory() . substr($path, 1); } return Preg::replaceCallback('#^(\$|(?P<percent>%))(?P<var>\w++)(?(percent)%)(?P<path>.*)#', static function ($matches): string { // Treat HOME as an alias for USERPROFILE on Windows for legacy reasons if (Platform::isWindows() && $matches['var'] === 'HOME') { if ((bool) Platform::getEnv('HOME')) { return Platform::getEnv('HOME') . $matches['path']; } return Platform::getEnv('USERPROFILE') . $matches['path']; } return Platform::getEnv($matches['var']) . $matches['path']; }, $path); } /** * @throws \RuntimeException If the user home could not reliably be determined * @return string The formal user home as detected from environment parameters */ public static function getUserDirectory(): string { if (false !== ($home = self::getEnv('HOME'))) { return $home; } if (self::isWindows() && false !== ($home = self::getEnv('USERPROFILE'))) { return $home; } if (\function_exists('posix_getuid') && \function_exists('posix_getpwuid')) { $info = posix_getpwuid(posix_getuid()); if (is_array($info)) { return $info['dir']; } } throw new \RuntimeException('Could not determine user directory'); } /** * @return bool Whether the host machine is running on the Windows Subsystem for Linux (WSL) */ public static function isWindowsSubsystemForLinux(): bool { if (null === self::$isWindowsSubsystemForLinux) { self::$isWindowsSubsystemForLinux = false; // while WSL will be hosted within windows, WSL itself cannot be windows based itself. if (self::isWindows()) { return self::$isWindowsSubsystemForLinux = false; } if ( !(bool) ini_get('open_basedir') && is_readable('/proc/version') && false !== stripos((string) Silencer::call('file_get_contents', '/proc/version'), 'microsoft') && !self::isDocker() // Docker and Podman running inside WSL should not be seen as WSL ) { return self::$isWindowsSubsystemForLinux = true; } } return self::$isWindowsSubsystemForLinux; } /** * @return bool Whether the host machine is running a Windows OS */ public static function isWindows(): bool { return \defined('PHP_WINDOWS_VERSION_BUILD'); } public static function isDocker(): bool { if (null !== self::$isDocker) { return self::$isDocker; } // cannot check so assume no if ((bool) ini_get('open_basedir')) { return self::$isDocker = false; } // .dockerenv and .containerenv are present in some cases but not reliably if (file_exists('/.dockerenv') || file_exists('/run/.containerenv') || file_exists('/var/run/.containerenv')) { return self::$isDocker = true; } // see https://www.baeldung.com/linux/is-process-running-inside-container $cgroups = [ '/proc/self/mountinfo', // cgroup v2 '/proc/1/cgroup', // cgroup v1 ]; foreach ($cgroups as $cgroup) { if (!is_readable($cgroup)) { continue; } // suppress errors as some environments have these files as readable but system restrictions prevent the read from succeeding // see https://github.com/composer/composer/issues/12095 try { $data = @file_get_contents($cgroup); } catch (\Throwable $e) { break; } if (!is_string($data)) { continue; } // detect default mount points created by Docker/containerd if (str_contains($data, '/var/lib/docker/') || str_contains($data, '/io.containerd.snapshotter')) { return self::$isDocker = true; } } return self::$isDocker = false; } /** * @return int return a guaranteed binary length of the string, regardless of silly mbstring configs */ public static function strlen(string $str): int { static $useMbString = null; if (null === $useMbString) { $useMbString = \function_exists('mb_strlen') && (bool) ini_get('mbstring.func_overload'); } if ($useMbString) { return mb_strlen($str, '8bit'); } return \strlen($str); } /** * @param ?resource $fd Open file descriptor or null to default to STDOUT */ public static function isTty($fd = null): bool { if ($fd === null) { $fd = defined('STDOUT') ? STDOUT : fopen('php://stdout', 'w'); if ($fd === false) { return false; } } // detect msysgit/mingw and assume this is a tty because detection // does not work correctly, see https://github.com/composer/composer/issues/9690 if (in_array(strtoupper((string) self::getEnv('MSYSTEM')), ['MINGW32', 'MINGW64'], true)) { return true; } // modern cross-platform function, includes the fstat // fallback so if it is present we trust it if (function_exists('stream_isatty')) { return stream_isatty($fd); } // only trusting this if it is positive, otherwise prefer fstat fallback if (function_exists('posix_isatty') && posix_isatty($fd)) { return true; } $stat = @fstat($fd); if ($stat === false) { return false; } // Check if formatted mode is S_IFCHR return 0020000 === ($stat['mode'] & 0170000); } /** * @return bool Whether the current command is for bash completion */ public static function isInputCompletionProcess(): bool { return '_complete' === ($_SERVER['argv'][1] ?? null); } public static function workaroundFilesystemIssues(): void { if (self::isVirtualBoxGuest()) { usleep(200000); } } /** * Attempts detection of VirtualBox guest VMs * * This works based on the process' user being "vagrant", the COMPOSER_RUNTIME_ENV env var being set to "virtualbox", or lsmod showing the virtualbox guest additions are loaded */ private static function isVirtualBoxGuest(): bool { if (null === self::$isVirtualBoxGuest) { self::$isVirtualBoxGuest = false; if (self::isWindows()) { return self::$isVirtualBoxGuest; } if (function_exists('posix_getpwuid') && function_exists('posix_geteuid')) { $processUser = posix_getpwuid(posix_geteuid()); if (is_array($processUser) && $processUser['name'] === 'vagrant') { return self::$isVirtualBoxGuest = true; } } if (self::getEnv('COMPOSER_RUNTIME_ENV') === 'virtualbox') { return self::$isVirtualBoxGuest = true; } if (defined('PHP_OS_FAMILY') && PHP_OS_FAMILY === 'Linux') { $process = new ProcessExecutor(); try { if (0 === $process->execute(['lsmod'], $output) && str_contains($output, 'vboxguest')) { return self::$isVirtualBoxGuest = true; } } catch (\Exception $e) { // noop } } } return self::$isVirtualBoxGuest; } /** * @return 'NUL'|'/dev/null' */ public static function getDevNull(): string { if (self::isWindows()) { return 'NUL'; } return '/dev/null'; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Silencer.php
src/Composer/Util/Silencer.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\Util; /** * Temporarily suppress PHP error reporting, usually warnings and below. * * @author Niels Keurentjes <niels.keurentjes@omines.com> */ class Silencer { /** * @var int[] Unpop stack */ private static $stack = []; /** * Suppresses given mask or errors. * * @param int|null $mask Error levels to suppress, default value NULL indicates all warnings and below. * @return int The old error reporting level. */ public static function suppress(?int $mask = null): int { if (!isset($mask)) { $mask = E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_DEPRECATED | E_USER_DEPRECATED; } $old = error_reporting(); self::$stack[] = $old; error_reporting($old & ~$mask); return $old; } /** * Restores a single state. */ public static function restore(): void { if (!empty(self::$stack)) { error_reporting(array_pop(self::$stack)); } } /** * Calls a specified function while silencing warnings and below. * * @param callable $callable Function to execute. * @param mixed $parameters Function to execute. * @throws \Exception Any exceptions from the callback are rethrown. * @return mixed Return value of the callback. */ public static function call(callable $callable, ...$parameters) { try { self::suppress(); $result = $callable(...$parameters); self::restore(); return $result; } catch (\Exception $e) { // Use a finally block for this when requirements are raised to PHP 5.5 self::restore(); throw $e; } } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/RemoteFilesystem.php
src/Composer/Util/RemoteFilesystem.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\Util; use Closure; use Composer\Config; use Composer\Downloader\MaxFileSizeExceededException; use Composer\IO\IOInterface; use Composer\Downloader\TransportException; use Composer\Pcre\Preg; use Composer\Util\Http\Response; use Composer\Util\Http\ProxyManager; /** * @internal * @author François Pluchino <francois.pluchino@opendisplay.com> * @author Jordi Boggiano <j.boggiano@seld.be> * @author Nils Adermann <naderman@naderman.de> */ class RemoteFilesystem { /** @var IOInterface */ private $io; /** @var Config */ private $config; /** @var string */ private $scheme; /** @var int */ private $bytesMax; /** @var string */ private $originUrl; /** @var non-empty-string */ private $fileUrl; /** @var ?string */ private $fileName; /** @var bool */ private $retry = false; /** @var bool */ private $progress; /** @var ?int */ private $lastProgress; /** @var mixed[] */ private $options = []; /** @var bool */ private $disableTls = false; /** @var list<string> */ private $lastHeaders; /** @var bool */ private $storeAuth = false; /** @var AuthHelper */ private $authHelper; /** @var bool */ private $degradedMode = false; /** @var int */ private $redirects; /** @var int */ private $maxRedirects = 20; /** * Constructor. * * @param IOInterface $io The IO instance * @param Config $config The config * @param mixed[] $options The options */ public function __construct(IOInterface $io, Config $config, array $options = [], bool $disableTls = false, ?AuthHelper $authHelper = null) { $this->io = $io; // Setup TLS options // The cafile option can be set via config.json if ($disableTls === false) { $this->options = StreamContextFactory::getTlsDefaults($options, $io); } else { $this->disableTls = true; } // handle the other externally set options normally. $this->options = array_replace_recursive($this->options, $options); $this->config = $config; $this->authHelper = $authHelper ?? new AuthHelper($io, $config); } /** * Copy the remote file in local. * * @param string $originUrl The origin URL * @param non-empty-string $fileUrl The file URL * @param string $fileName the local filename * @param bool $progress Display the progression * @param mixed[] $options Additional context options * * @return bool true */ public function copy(string $originUrl, string $fileUrl, string $fileName, bool $progress = true, array $options = []) { return $this->get($originUrl, $fileUrl, $options, $fileName, $progress); } /** * Get the content. * * @param string $originUrl The origin URL * @param non-empty-string $fileUrl The file URL * @param bool $progress Display the progression * @param mixed[] $options Additional context options * * @return bool|string The content */ public function getContents(string $originUrl, string $fileUrl, bool $progress = true, array $options = []) { return $this->get($originUrl, $fileUrl, $options, null, $progress); } /** * Retrieve the options set in the constructor * * @return mixed[] Options */ public function getOptions() { return $this->options; } /** * Merges new options * * @param mixed[] $options * @return void */ public function setOptions(array $options) { $this->options = array_replace_recursive($this->options, $options); } /** * Check is disable TLS. * * @return bool */ public function isTlsDisabled() { return $this->disableTls === true; } /** * Returns the headers of the last request * * @return list<string> */ public function getLastHeaders() { return $this->lastHeaders; } /** * @param string[] $headers array of returned headers like from getLastHeaders() * @return int|null */ public static function findStatusCode(array $headers) { $value = null; foreach ($headers as $header) { if (Preg::isMatch('{^HTTP/\S+ (\d+)}i', $header, $match)) { // In case of redirects, http_response_headers contains the headers of all responses // so we can not return directly and need to keep iterating $value = (int) $match[1]; } } return $value; } /** * @param string[] $headers array of returned headers like from getLastHeaders() * @return string|null */ public function findStatusMessage(array $headers) { $value = null; foreach ($headers as $header) { if (Preg::isMatch('{^HTTP/\S+ \d+}i', $header)) { // In case of redirects, http_response_headers contains the headers of all responses // so we can not return directly and need to keep iterating $value = $header; } } return $value; } /** * Get file content or copy action. * * @param string $originUrl The origin URL * @param non-empty-string $fileUrl The file URL * @param mixed[] $additionalOptions context options * @param string $fileName the local filename * @param bool $progress Display the progression * * @throws TransportException|\Exception * @throws TransportException When the file could not be downloaded * * @return bool|string */ protected function get(string $originUrl, string $fileUrl, array $additionalOptions = [], ?string $fileName = null, bool $progress = true) { $this->scheme = parse_url(strtr($fileUrl, '\\', '/'), PHP_URL_SCHEME); $this->bytesMax = 0; $this->originUrl = $originUrl; $this->fileUrl = $fileUrl; $this->fileName = $fileName; $this->progress = $progress; $this->lastProgress = null; $retryAuthFailure = true; $this->lastHeaders = []; $this->redirects = 1; // The first request counts. $tempAdditionalOptions = $additionalOptions; if (isset($tempAdditionalOptions['retry-auth-failure'])) { $retryAuthFailure = (bool) $tempAdditionalOptions['retry-auth-failure']; unset($tempAdditionalOptions['retry-auth-failure']); } $isRedirect = false; if (isset($tempAdditionalOptions['redirects'])) { $this->redirects = $tempAdditionalOptions['redirects']; $isRedirect = true; unset($tempAdditionalOptions['redirects']); } $options = $this->getOptionsForUrl($originUrl, $tempAdditionalOptions); unset($tempAdditionalOptions); $origFileUrl = $fileUrl; if (isset($options['prevent_ip_access_callable'])) { throw new \RuntimeException("RemoteFilesystem doesn't support the 'prevent_ip_access_callable' config."); } if (isset($options['gitlab-token'])) { $fileUrl .= (false === strpos($fileUrl, '?') ? '?' : '&') . 'access_token='.$options['gitlab-token']; unset($options['gitlab-token']); } if (isset($options['http'])) { $options['http']['ignore_errors'] = true; } if ($this->degradedMode && strpos($fileUrl, 'http://repo.packagist.org/') === 0) { // access packagist using the resolved IPv4 instead of the hostname to force IPv4 protocol $fileUrl = 'http://' . gethostbyname('repo.packagist.org') . substr($fileUrl, 20); $degradedPackagist = true; } $maxFileSize = null; if (isset($options['max_file_size'])) { $maxFileSize = $options['max_file_size']; unset($options['max_file_size']); } $ctx = StreamContextFactory::getContext($fileUrl, $options, ['notification' => Closure::fromCallable([$this, 'callbackGet'])]); $proxy = ProxyManager::getInstance()->getProxyForRequest($fileUrl); $usingProxy = $proxy->getStatus(' using proxy (%s)'); $this->io->writeError((strpos($origFileUrl, 'http') === 0 ? 'Downloading ' : 'Reading ') . Url::sanitize($origFileUrl) . $usingProxy, true, IOInterface::DEBUG); unset($origFileUrl, $proxy, $usingProxy); // Check for secure HTTP, but allow insecure Packagist calls to $hashed providers as file integrity is verified with sha256 if ((!Preg::isMatch('{^http://(repo\.)?packagist\.org/p/}', $fileUrl) || (false === strpos($fileUrl, '$') && false === strpos($fileUrl, '%24'))) && empty($degradedPackagist)) { $this->config->prohibitUrlByConfig($fileUrl, $this->io); } if ($this->progress && !$isRedirect) { $this->io->writeError("Downloading (<comment>connecting...</comment>)", false); } $errorMessage = ''; $errorCode = 0; $result = false; set_error_handler(static function ($code, $msg) use (&$errorMessage): bool { if ($errorMessage) { $errorMessage .= "\n"; } $errorMessage .= Preg::replace('{^file_get_contents\(.*?\): }', '', $msg); return true; }); $http_response_header = []; try { $result = $this->getRemoteContents($originUrl, $fileUrl, $ctx, $http_response_header, $maxFileSize); if (!empty($http_response_header[0])) { $statusCode = self::findStatusCode($http_response_header); if ($statusCode >= 300 && Response::findHeaderValue($http_response_header, 'content-type') === 'application/json') { HttpDownloader::outputWarnings($this->io, $originUrl, json_decode($result, true)); } if (in_array($statusCode, [401, 403]) && $retryAuthFailure) { $this->promptAuthAndRetry($statusCode, $this->findStatusMessage($http_response_header), $http_response_header); } } $contentLength = !empty($http_response_header[0]) ? Response::findHeaderValue($http_response_header, 'content-length') : null; if ($contentLength && Platform::strlen($result) < $contentLength) { // alas, this is not possible via the stream callback because STREAM_NOTIFY_COMPLETED is documented, but not implemented anywhere in PHP $e = new TransportException('Content-Length mismatch, received '.Platform::strlen($result).' bytes out of the expected '.$contentLength); $e->setHeaders($http_response_header); $e->setStatusCode(self::findStatusCode($http_response_header)); try { $e->setResponse($this->decodeResult($result, $http_response_header)); } catch (\Exception $discarded) { $e->setResponse($this->normalizeResult($result)); } $this->io->writeError('Content-Length mismatch, received '.Platform::strlen($result).' out of '.$contentLength.' bytes: (' . base64_encode($result).')', true, IOInterface::DEBUG); throw $e; } } catch (\Exception $e) { if ($e instanceof TransportException && !empty($http_response_header[0])) { $e->setHeaders($http_response_header); $e->setStatusCode(self::findStatusCode($http_response_header)); } if ($e instanceof TransportException && $result !== false) { $e->setResponse($this->decodeResult($result, $http_response_header)); } $result = false; } if ($errorMessage && !filter_var(ini_get('allow_url_fopen'), FILTER_VALIDATE_BOOLEAN)) { $errorMessage = 'allow_url_fopen must be enabled in php.ini ('.$errorMessage.')'; } restore_error_handler(); if (isset($e) && !$this->retry) { if (!$this->degradedMode && false !== strpos($e->getMessage(), 'Operation timed out')) { $this->degradedMode = true; $this->io->writeError(''); $this->io->writeError([ '<error>'.$e->getMessage().'</error>', '<error>Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info</error>', ]); return $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress); } throw $e; } $statusCode = null; $contentType = null; $locationHeader = null; if (!empty($http_response_header[0])) { $statusCode = self::findStatusCode($http_response_header); $contentType = Response::findHeaderValue($http_response_header, 'content-type'); $locationHeader = Response::findHeaderValue($http_response_header, 'location'); } // check for bitbucket login page asking to authenticate if ($originUrl === 'bitbucket.org' && !$this->authHelper->isPublicBitBucketDownload($fileUrl) && substr($fileUrl, -4) === '.zip' && (!$locationHeader || substr(parse_url($locationHeader, PHP_URL_PATH), -4) !== '.zip') && $contentType && Preg::isMatch('{^text/html\b}i', $contentType) ) { $result = false; if ($retryAuthFailure) { $this->promptAuthAndRetry(401); } } // check for gitlab 404 when downloading archives if ($statusCode === 404 && in_array($originUrl, $this->config->get('gitlab-domains'), true) && false !== strpos($fileUrl, 'archive.zip') ) { $result = false; if ($retryAuthFailure) { $this->promptAuthAndRetry(401); } } // handle 3xx redirects, 304 Not Modified is excluded $hasFollowedRedirect = false; if ($statusCode >= 300 && $statusCode <= 399 && $statusCode !== 304 && $this->redirects < $this->maxRedirects) { $hasFollowedRedirect = true; $result = $this->handleRedirect($http_response_header, $additionalOptions, $result); } // fail 4xx and 5xx responses and capture the response if ($statusCode && $statusCode >= 400 && $statusCode <= 599) { if (!$this->retry) { if ($this->progress && !$isRedirect) { $this->io->overwriteError("Downloading (<error>failed</error>)", false); } $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded ('.$http_response_header[0].')', $statusCode); $e->setHeaders($http_response_header); $e->setResponse($this->decodeResult($result, $http_response_header)); $e->setStatusCode($statusCode); throw $e; } $result = false; } if ($this->progress && !$this->retry && !$isRedirect) { $this->io->overwriteError("Downloading (".($result === false ? '<error>failed</error>' : '<comment>100%</comment>').")", false); } // decode gzip if ($result && extension_loaded('zlib') && strpos($fileUrl, 'http') === 0 && !$hasFollowedRedirect) { try { $result = $this->decodeResult($result, $http_response_header); } catch (\Exception $e) { if ($this->degradedMode) { throw $e; } $this->degradedMode = true; $this->io->writeError([ '', '<error>Failed to decode response: '.$e->getMessage().'</error>', '<error>Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info</error>', ]); return $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress); } } // handle copy command if download was successful if (false !== $result && null !== $fileName && !$isRedirect) { if ('' === $result) { throw new TransportException('"'.$this->fileUrl.'" appears broken, and returned an empty 200 response'); } $errorMessage = ''; set_error_handler(static function ($code, $msg) use (&$errorMessage): bool { if ($errorMessage) { $errorMessage .= "\n"; } $errorMessage .= Preg::replace('{^file_put_contents\(.*?\): }', '', $msg); return true; }); $result = (bool) file_put_contents($fileName, $result); restore_error_handler(); if (false === $result) { throw new TransportException('The "'.$this->fileUrl.'" file could not be written to '.$fileName.': '.$errorMessage); } } if ($this->retry) { $this->retry = false; $result = $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress); if ($this->storeAuth) { $this->authHelper->storeAuth($this->originUrl, $this->storeAuth); $this->storeAuth = false; } return $result; } if (false === $result) { $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded: '.$errorMessage, $errorCode); if (!empty($http_response_header[0])) { $e->setHeaders($http_response_header); } if (!$this->degradedMode && false !== strpos($e->getMessage(), 'Operation timed out')) { $this->degradedMode = true; $this->io->writeError(''); $this->io->writeError([ '<error>'.$e->getMessage().'</error>', '<error>Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info</error>', ]); return $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress); } throw $e; } if (!empty($http_response_header[0])) { $this->lastHeaders = $http_response_header; } return $result; } /** * Get contents of remote URL. * * @param string $originUrl The origin URL * @param string $fileUrl The file URL * @param resource $context The stream context * @param string[] $responseHeaders * @param int $maxFileSize The maximum allowed file size * * @return string|false The response contents or false on failure * * @param-out list<string> $responseHeaders */ protected function getRemoteContents(string $originUrl, string $fileUrl, $context, ?array &$responseHeaders = null, ?int $maxFileSize = null) { $result = false; if (\PHP_VERSION_ID >= 80400) { http_clear_last_response_headers(); } try { $e = null; if ($maxFileSize !== null) { $result = file_get_contents($fileUrl, false, $context, 0, $maxFileSize); } else { // passing `null` to file_get_contents will convert `null` to `0` and return 0 bytes $result = file_get_contents($fileUrl, false, $context); } } catch (\Throwable $e) { } if ($result !== false && $maxFileSize !== null && Platform::strlen($result) >= $maxFileSize) { throw new MaxFileSizeExceededException('Maximum allowed download size reached. Downloaded ' . Platform::strlen($result) . ' of allowed ' . $maxFileSize . ' bytes'); } // https://www.php.net/manual/en/reserved.variables.httpresponseheader.php if (\PHP_VERSION_ID >= 80400) { $responseHeaders = http_get_last_response_headers() ?? []; http_clear_last_response_headers(); } else { $responseHeaders = $http_response_header ?? []; } if (null !== $e) { throw $e; } return $result; } /** * Get notification action. * * @param int $notificationCode The notification code * @param int $severity The severity level * @param string $message The message * @param int $messageCode The message code * @param int $bytesTransferred The loaded size * @param int $bytesMax The total size * * @return void * * @throws TransportException */ protected function callbackGet(int $notificationCode, int $severity, ?string $message, int $messageCode, int $bytesTransferred, int $bytesMax) { switch ($notificationCode) { case STREAM_NOTIFY_FAILURE: if (400 === $messageCode) { // This might happen if your host is secured by ssl client certificate authentication // but you do not send an appropriate certificate throw new TransportException("The '" . $this->fileUrl . "' URL could not be accessed: " . $message, $messageCode); } break; case STREAM_NOTIFY_FILE_SIZE_IS: $this->bytesMax = $bytesMax; break; case STREAM_NOTIFY_PROGRESS: if ($this->bytesMax > 0 && $this->progress) { $progression = min(100, (int) round($bytesTransferred / $this->bytesMax * 100)); if ((0 === $progression % 5) && 100 !== $progression && $progression !== $this->lastProgress) { $this->lastProgress = $progression; $this->io->overwriteError("Downloading (<comment>$progression%</comment>)", false); } } break; default: break; } } /** * @param positive-int $httpStatus * @param string[] $headers * * @return void */ protected function promptAuthAndRetry($httpStatus, ?string $reason = null, array $headers = []) { $result = $this->authHelper->promptAuthIfNeeded($this->fileUrl, $this->originUrl, $httpStatus, $reason, $headers, 1 /** always pass 1 as RemoteFilesystem is single threaded there is no race condition possible */); $this->storeAuth = $result['storeAuth']; $this->retry = $result['retry']; if ($this->retry) { throw new TransportException('RETRY'); } } /** * @param mixed[] $additionalOptions * * @return mixed[] */ protected function getOptionsForUrl(string $originUrl, array $additionalOptions) { $tlsOptions = []; $headers = []; if (extension_loaded('zlib')) { $headers[] = 'Accept-Encoding: gzip'; } $options = array_replace_recursive($this->options, $tlsOptions, $additionalOptions); if (!$this->degradedMode) { // degraded mode disables HTTP/1.1 which causes issues with some bad // proxies/software due to the use of chunked encoding $options['http']['protocol_version'] = 1.1; $headers[] = 'Connection: close'; } if (isset($options['http']['header']) && !is_array($options['http']['header'])) { $options['http']['header'] = explode("\r\n", trim($options['http']['header'], "\r\n")); } $options = $this->authHelper->addAuthenticationOptions($options, $originUrl, $this->fileUrl); $options['http']['follow_location'] = 0; foreach ($headers as $header) { $options['http']['header'][] = $header; } return $options; } /** * @param string[] $responseHeaders * @param mixed[] $additionalOptions * @param string|false $result * * @return bool|string */ private function handleRedirect(array $responseHeaders, array $additionalOptions, $result) { if ($locationHeader = Response::findHeaderValue($responseHeaders, 'location')) { if (parse_url($locationHeader, PHP_URL_SCHEME)) { // Absolute URL; e.g. https://example.com/composer $targetUrl = $locationHeader; } elseif (parse_url($locationHeader, PHP_URL_HOST)) { // Scheme relative; e.g. //example.com/foo $targetUrl = $this->scheme.':'.$locationHeader; } elseif ('/' === $locationHeader[0]) { // Absolute path; e.g. /foo $urlHost = parse_url($this->fileUrl, PHP_URL_HOST); // Replace path using hostname as an anchor. $targetUrl = Preg::replace('{^(.+(?://|@)'.preg_quote($urlHost).'(?::\d+)?)(?:[/\?].*)?$}', '\1'.$locationHeader, $this->fileUrl); } else { // Relative path; e.g. foo // This actually differs from PHP which seems to add duplicate slashes. $targetUrl = Preg::replace('{^(.+/)[^/?]*(?:\?.*)?$}', '\1'.$locationHeader, $this->fileUrl); } } if (!empty($targetUrl)) { $this->redirects++; $this->io->writeError('', true, IOInterface::DEBUG); $this->io->writeError(sprintf('Following redirect (%u) %s', $this->redirects, Url::sanitize($targetUrl)), true, IOInterface::DEBUG); $additionalOptions['redirects'] = $this->redirects; return $this->get(parse_url($targetUrl, PHP_URL_HOST), $targetUrl, $additionalOptions, $this->fileName, $this->progress); } if (!$this->retry) { $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded, got redirect without Location ('.$responseHeaders[0].')'); $e->setHeaders($responseHeaders); $e->setResponse($this->decodeResult($result, $responseHeaders)); throw $e; } return false; } /** * @param string|false $result * @param string[] $responseHeaders */ private function decodeResult($result, array $responseHeaders): ?string { // decode gzip if ($result && extension_loaded('zlib')) { $contentEncoding = Response::findHeaderValue($responseHeaders, 'content-encoding'); $decode = $contentEncoding && 'gzip' === strtolower($contentEncoding); if ($decode) { $result = zlib_decode($result); if ($result === false) { throw new TransportException('Failed to decode zlib stream'); } } } return $this->normalizeResult($result); } /** * @param string|false $result */ private function normalizeResult($result): ?string { if ($result === false) { return null; } return $result; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/ConfigValidator.php
src/Composer/Util/ConfigValidator.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\Util; use Composer\Package\Loader\ArrayLoader; use Composer\Package\Loader\ValidatingArrayLoader; use Composer\Package\Loader\InvalidPackageException; use Composer\Json\JsonValidationException; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\Pcre\Preg; use Composer\Spdx\SpdxLicenses; use Seld\JsonLint\DuplicateKeyException; use Seld\JsonLint\JsonParser; /** * Validates a composer configuration. * * @author Robert Schönthal <seroscho@googlemail.com> * @author Jordi Boggiano <j.boggiano@seld.be> */ class ConfigValidator { public const CHECK_VERSION = 1; /** @var IOInterface */ private $io; public function __construct(IOInterface $io) { $this->io = $io; } /** * Validates the config, and returns the result. * * @param string $file The path to the file * @param int $arrayLoaderValidationFlags Flags for ArrayLoader validation * @param int $flags Flags for validation * * @return array{list<string>, list<string>, list<string>} a triple containing the errors, publishable errors, and warnings */ public function validate(string $file, int $arrayLoaderValidationFlags = ValidatingArrayLoader::CHECK_ALL, int $flags = self::CHECK_VERSION): array { $errors = []; $publishErrors = []; $warnings = []; // validate json schema $laxValid = false; $manifest = null; try { $json = new JsonFile($file, null, $this->io); $manifest = $json->read(); $json->validateSchema(JsonFile::LAX_SCHEMA); $laxValid = true; $json->validateSchema(); } catch (JsonValidationException $e) { foreach ($e->getErrors() as $message) { if ($laxValid) { $publishErrors[] = $message; } else { $errors[] = $message; } } } catch (\Exception $e) { $errors[] = $e->getMessage(); return [$errors, $publishErrors, $warnings]; } if (is_array($manifest)) { $jsonParser = new JsonParser(); try { $jsonParser->parse((string) file_get_contents($file), JsonParser::DETECT_KEY_CONFLICTS); } catch (DuplicateKeyException $e) { $details = $e->getDetails(); $warnings[] = 'Key '.$details['key'].' is a duplicate in '.$file.' at line '.$details['line']; } } // validate actual data if (empty($manifest['license'])) { $warnings[] = 'No license specified, it is recommended to do so. For closed-source software you may use "proprietary" as license.'; } else { $licenses = (array) $manifest['license']; // strip proprietary since it's not a valid SPDX identifier, but is accepted by composer foreach ($licenses as $key => $license) { if ('proprietary' === $license) { unset($licenses[$key]); } } $licenseValidator = new SpdxLicenses(); foreach ($licenses as $license) { $spdxLicense = $licenseValidator->getLicenseByIdentifier($license); if ($spdxLicense && $spdxLicense[3]) { if (Preg::isMatch('{^[AL]?GPL-[123](\.[01])?\+$}i', $license)) { $warnings[] = sprintf( 'License "%s" is a deprecated SPDX license identifier, use "'.str_replace('+', '', $license).'-or-later" instead', $license ); } elseif (Preg::isMatch('{^[AL]?GPL-[123](\.[01])?$}i', $license)) { $warnings[] = sprintf( 'License "%s" is a deprecated SPDX license identifier, use "'.$license.'-only" or "'.$license.'-or-later" instead', $license ); } else { $warnings[] = sprintf( 'License "%s" is a deprecated SPDX license identifier, see https://spdx.org/licenses/', $license ); } } } } if (($flags & self::CHECK_VERSION) && isset($manifest['version'])) { $warnings[] = 'The version field is present, it is recommended to leave it out if the package is published on Packagist.'; } if (!empty($manifest['name']) && Preg::isMatch('{[A-Z]}', $manifest['name'])) { $suggestName = Preg::replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $manifest['name']); $suggestName = strtolower($suggestName); $publishErrors[] = sprintf( 'Name "%s" does not match the best practice (e.g. lower-cased/with-dashes). We suggest using "%s" instead. As such you will not be able to submit it to Packagist.', $manifest['name'], $suggestName ); } if (!empty($manifest['type']) && $manifest['type'] === 'composer-installer') { $warnings[] = "The package type 'composer-installer' is deprecated. Please distribute your custom installers as plugins from now on. See https://getcomposer.org/doc/articles/plugins.md for plugin documentation."; } // check for require-dev overrides if (isset($manifest['require'], $manifest['require-dev'])) { $requireOverrides = array_intersect_key($manifest['require'], $manifest['require-dev']); if (!empty($requireOverrides)) { $plural = (count($requireOverrides) > 1) ? 'are' : 'is'; $warnings[] = implode(', ', array_keys($requireOverrides)). " {$plural} required both in require and require-dev, this can lead to unexpected behavior"; } } // check for meaningless provide/replace satisfying requirements foreach (['provide', 'replace'] as $linkType) { if (isset($manifest[$linkType])) { foreach (['require', 'require-dev'] as $requireType) { if (isset($manifest[$requireType])) { foreach ($manifest[$linkType] as $provide => $constraint) { if (isset($manifest[$requireType][$provide])) { $warnings[] = 'The package ' . $provide . ' in '.$requireType.' is also listed in '.$linkType.' which satisfies the requirement. Remove it from '.$linkType.' if you wish to install it.'; } } } } } } // check for commit references $require = $manifest['require'] ?? []; $requireDev = $manifest['require-dev'] ?? []; $packages = array_merge($require, $requireDev); foreach ($packages as $package => $version) { if (Preg::isMatch('/#/', $version)) { $warnings[] = sprintf( 'The package "%s" is pointing to a commit-ref, this is bad practice and can cause unforeseen issues.', $package ); } } // report scripts-descriptions for non-existent scripts $scriptsDescriptions = $manifest['scripts-descriptions'] ?? []; $scripts = $manifest['scripts'] ?? []; foreach ($scriptsDescriptions as $scriptName => $scriptDescription) { if (!array_key_exists($scriptName, $scripts)) { $warnings[] = sprintf( 'Description for non-existent script "%s" found in "scripts-descriptions"', $scriptName ); } } // report scripts-aliases for non-existent scripts $scriptAliases = $manifest['scripts-aliases'] ?? []; foreach ($scriptAliases as $scriptName => $scriptAlias) { if (!array_key_exists($scriptName, $scripts)) { $warnings[] = sprintf( 'Aliases for non-existent script "%s" found in "scripts-aliases"', $scriptName ); } } // check for empty psr-0/psr-4 namespace prefixes if (isset($manifest['autoload']['psr-0'][''])) { $warnings[] = "Defining autoload.psr-0 with an empty namespace prefix is a bad idea for performance"; } if (isset($manifest['autoload']['psr-4'][''])) { $warnings[] = "Defining autoload.psr-4 with an empty namespace prefix is a bad idea for performance"; } $loader = new ValidatingArrayLoader(new ArrayLoader(), true, null, $arrayLoaderValidationFlags); try { if (!isset($manifest['version'])) { $manifest['version'] = '1.0.0'; } if (!isset($manifest['name'])) { $manifest['name'] = 'dummy/dummy'; } $loader->load($manifest); } catch (InvalidPackageException $e) { $errors = array_merge($errors, $e->getErrors()); } $warnings = array_merge($warnings, $loader->getWarnings()); return [$errors, $publishErrors, $warnings]; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/ForgejoUrl.php
src/Composer/Util/ForgejoUrl.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\Util; use Composer\Pcre\Preg; /** * @internal * @readonly */ final class ForgejoUrl { public const URL_REGEX = '{^(?:(?:https?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/([^/]+?)(?:\.git|/)?$}'; /** @var string */ public $owner; /** @var string */ public $repository; /** @var string */ public $originUrl; /** @var string */ public $apiUrl; private function __construct( string $owner, string $repository, string $originUrl, string $apiUrl ) { $this->owner = $owner; $this->repository = $repository; $this->originUrl = $originUrl; $this->apiUrl = $apiUrl; } public static function create(string $repoUrl): self { $url = self::tryFrom($repoUrl); if ($url !== null) { return $url; } throw new \InvalidArgumentException('This is not a valid Forgejo URL: ' . $repoUrl); } public static function tryFrom(?string $repoUrl): ?self { if ($repoUrl === null || !Preg::isMatch(self::URL_REGEX, $repoUrl, $match)) { return null; } $originUrl = strtolower($match[1] ?? (string) $match[2]); $apiBase = $originUrl . '/api/v1'; return new self( $match[3], $match[4], $originUrl, sprintf('https://%s/repos/%s/%s', $apiBase, $match[3], $match[4]) ); } public function generateSshUrl(): string { return 'git@' . $this->originUrl . ':'.$this->owner.'/'.$this->repository.'.git'; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Bitbucket.php
src/Composer/Util/Bitbucket.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\Util; use Composer\Factory; use Composer\IO\IOInterface; use Composer\Config; use Composer\Downloader\TransportException; /** * @author Paul Wenke <wenke.paul@gmail.com> */ class Bitbucket { /** @var IOInterface */ private $io; /** @var Config */ private $config; /** @var ProcessExecutor */ private $process; /** @var HttpDownloader */ private $httpDownloader; /** @var array{access_token: string, expires_in?: int}|null */ private $token = null; /** @var int|null */ private $time; public const OAUTH2_ACCESS_TOKEN_URL = 'https://bitbucket.org/site/oauth2/access_token'; /** * Constructor. * * @param IOInterface $io The IO instance * @param Config $config The composer configuration * @param ProcessExecutor $process Process instance, injectable for mocking * @param HttpDownloader $httpDownloader Remote Filesystem, injectable for mocking * @param int $time Timestamp, injectable for mocking */ public function __construct(IOInterface $io, Config $config, ?ProcessExecutor $process = null, ?HttpDownloader $httpDownloader = null, ?int $time = null) { $this->io = $io; $this->config = $config; $this->process = $process ?: new ProcessExecutor($io); $this->httpDownloader = $httpDownloader ?: Factory::createHttpDownloader($this->io, $config); $this->time = $time; } public function getToken(): string { if (!isset($this->token['access_token'])) { return ''; } return $this->token['access_token']; } /** * Attempts to authorize a Bitbucket domain via OAuth * * @param string $originUrl The host this Bitbucket instance is located at * @return bool true on success */ public function authorizeOAuth(string $originUrl): bool { if ($originUrl !== 'bitbucket.org') { return false; } // if available use token from git config if (0 === $this->process->execute(['git', 'config', 'bitbucket.accesstoken'], $output)) { $this->io->setAuthentication($originUrl, 'x-token-auth', trim($output)); return true; } return false; } private function requestAccessToken(): bool { try { $response = $this->httpDownloader->get(self::OAUTH2_ACCESS_TOKEN_URL, [ 'retry-auth-failure' => false, 'http' => [ 'method' => 'POST', 'content' => 'grant_type=client_credentials', ], ]); $token = $response->decodeJson(); if (!isset($token['expires_in']) || !isset($token['access_token'])) { throw new \LogicException('Expected a token configured with expires_in and access_token present, got '.json_encode($token)); } $this->token = $token; } catch (TransportException $e) { if ($e->getCode() === 400) { $this->io->writeError('<error>Invalid OAuth consumer provided.</error>'); $this->io->writeError('This can have three reasons:'); $this->io->writeError('1. You are authenticating with a bitbucket username/password combination'); $this->io->writeError('2. You are using an OAuth consumer, but didn\'t configure a (dummy) callback url'); $this->io->writeError('3. You are using an OAuth consumer, but didn\'t configure it as private consumer'); return false; } if (in_array($e->getCode(), [403, 401])) { $this->io->writeError('<error>Invalid OAuth consumer provided.</error>'); $this->io->writeError('You can also add it manually later by using "composer config --global --auth bitbucket-oauth.bitbucket.org <consumer-key> <consumer-secret>"'); return false; } throw $e; } return true; } /** * Authorizes a Bitbucket domain interactively via OAuth * * @param string $originUrl The host this Bitbucket instance is located at * @param string $message The reason this authorization is required * @throws \RuntimeException * @throws TransportException|\Exception * @return bool true on success */ public function authorizeOAuthInteractively(string $originUrl, ?string $message = null): bool { if ($message) { $this->io->writeError($message); } $localAuthConfig = $this->config->getLocalAuthConfigSource(); $url = 'https://support.atlassian.com/bitbucket-cloud/docs/use-oauth-on-bitbucket-cloud/'; $this->io->writeError('Follow the instructions here:'); $this->io->writeError($url); $this->io->writeError(sprintf('to create a consumer. It will be stored in "%s" for future use by Composer.', ($localAuthConfig !== null ? $localAuthConfig->getName() . ' OR ' : '') . $this->config->getAuthConfigSource()->getName())); $this->io->writeError('Ensure you enter a "Callback URL" (http://example.com is fine) or it will not be possible to create an Access Token (this callback url will not be used by composer)'); $storeInLocalAuthConfig = false; if ($localAuthConfig !== null) { $storeInLocalAuthConfig = $this->io->askConfirmation('A local auth config source was found, do you want to store the token there?', true); } $consumerKey = trim((string) $this->io->askAndHideAnswer('Consumer Key (hidden): ')); if (!$consumerKey) { $this->io->writeError('<warning>No consumer key given, aborting.</warning>'); $this->io->writeError('You can also add it manually later by using "composer config --global --auth bitbucket-oauth.bitbucket.org <consumer-key> <consumer-secret>"'); return false; } $consumerSecret = trim((string) $this->io->askAndHideAnswer('Consumer Secret (hidden): ')); if (!$consumerSecret) { $this->io->writeError('<warning>No consumer secret given, aborting.</warning>'); $this->io->writeError('You can also add it manually later by using "composer config --global --auth bitbucket-oauth.bitbucket.org <consumer-key> <consumer-secret>"'); return false; } $this->io->setAuthentication($originUrl, $consumerKey, $consumerSecret); if (!$this->requestAccessToken()) { return false; } // store value in user config $authConfigSource = $storeInLocalAuthConfig && $localAuthConfig !== null ? $localAuthConfig : $this->config->getAuthConfigSource(); $this->storeInAuthConfig($authConfigSource, $originUrl, $consumerKey, $consumerSecret); // Remove conflicting basic auth credentials (if available) $this->config->getAuthConfigSource()->removeConfigSetting('http-basic.' . $originUrl); $this->io->writeError('<info>Consumer stored successfully.</info>'); return true; } /** * Retrieves an access token from Bitbucket. */ public function requestToken(string $originUrl, string $consumerKey, string $consumerSecret): string { if ($this->token !== null || $this->getTokenFromConfig($originUrl)) { return $this->token['access_token']; } $this->io->setAuthentication($originUrl, $consumerKey, $consumerSecret); if (!$this->requestAccessToken()) { return ''; } $this->storeInAuthConfig($this->config->getLocalAuthConfigSource() ?? $this->config->getAuthConfigSource(), $originUrl, $consumerKey, $consumerSecret); if (!isset($this->token['access_token'])) { throw new \LogicException('Failed to initialize token above'); } return $this->token['access_token']; } /** * Store the new/updated credentials to the configuration */ private function storeInAuthConfig(Config\ConfigSourceInterface $authConfigSource, string $originUrl, string $consumerKey, string $consumerSecret): void { $this->config->getConfigSource()->removeConfigSetting('bitbucket-oauth.'.$originUrl); if (null === $this->token || !isset($this->token['expires_in'])) { throw new \LogicException('Expected a token configured with expires_in present, got '.json_encode($this->token)); } $time = null === $this->time ? time() : $this->time; $consumer = [ "consumer-key" => $consumerKey, "consumer-secret" => $consumerSecret, "access-token" => $this->token['access_token'], "access-token-expiration" => $time + $this->token['expires_in'], ]; $this->config->getAuthConfigSource()->addConfigSetting('bitbucket-oauth.'.$originUrl, $consumer); } /** * @phpstan-assert-if-true array{access_token: string} $this->token */ private function getTokenFromConfig(string $originUrl): bool { $authConfig = $this->config->get('bitbucket-oauth'); if ( !isset($authConfig[$originUrl]['access-token'], $authConfig[$originUrl]['access-token-expiration']) || time() > $authConfig[$originUrl]['access-token-expiration'] ) { return false; } $this->token = [ 'access_token' => $authConfig[$originUrl]['access-token'], ]; return true; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/TlsHelper.php
src/Composer/Util/TlsHelper.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\Util; use Composer\CaBundle\CaBundle; use Composer\Pcre\Preg; /** * @author Chris Smith <chris@cs278.org> * @deprecated Use composer/ca-bundle and composer/composer 2.2 if you still need PHP 5 compatibility, this class will be removed in Composer 3.0 */ final class TlsHelper { /** * Match hostname against a certificate. * * @param mixed $certificate X.509 certificate * @param string $hostname Hostname in the URL * @param string $cn Set to the common name of the certificate iff match found */ public static function checkCertificateHost($certificate, string $hostname, ?string &$cn = null): bool { $names = self::getCertificateNames($certificate); if (empty($names)) { return false; } $combinedNames = array_merge($names['san'], [$names['cn']]); $hostname = strtolower($hostname); foreach ($combinedNames as $certName) { $matcher = self::certNameMatcher($certName); if ($matcher && $matcher($hostname)) { $cn = $names['cn']; return true; } } return false; } /** * Extract DNS names out of an X.509 certificate. * * @param mixed $certificate X.509 certificate * * @return array{cn: string, san: string[]}|null */ public static function getCertificateNames($certificate): ?array { if (is_array($certificate)) { $info = $certificate; } elseif (CaBundle::isOpensslParseSafe()) { $info = openssl_x509_parse($certificate, false); } if (!isset($info['subject']['commonName'])) { return null; } $commonName = strtolower($info['subject']['commonName']); $subjectAltNames = []; if (isset($info['extensions']['subjectAltName'])) { $subjectAltNames = Preg::split('{\s*,\s*}', $info['extensions']['subjectAltName']); $subjectAltNames = array_filter( array_map(static function ($name): ?string { if (0 === strpos($name, 'DNS:')) { return strtolower(ltrim(substr($name, 4))); } return null; }, $subjectAltNames), static function (?string $san) { return $san !== null; } ); $subjectAltNames = array_values($subjectAltNames); } return [ 'cn' => $commonName, 'san' => $subjectAltNames, ]; } /** * Get the certificate pin. * * By Kevin McArthur of StormTide Digital Studios Inc. * @KevinSMcArthur / https://github.com/StormTide * * See https://tools.ietf.org/html/draft-ietf-websec-key-pinning-02 * * This method was adapted from Sslurp. * https://github.com/EvanDotPro/Sslurp * * (c) Evan Coury <me@evancoury.com> * * For the full copyright and license information, please see below: * * Copyright (c) 2013, Evan Coury * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public static function getCertificateFingerprint(string $certificate): string { $pubkey = openssl_get_publickey($certificate); if ($pubkey === false) { throw new \RuntimeException('Failed to retrieve the public key from certificate'); } $pubkeydetails = openssl_pkey_get_details($pubkey); $pubkeypem = $pubkeydetails['key']; //Convert PEM to DER before SHA1'ing $start = '-----BEGIN PUBLIC KEY-----'; $end = '-----END PUBLIC KEY-----'; $pemtrim = substr($pubkeypem, strpos($pubkeypem, $start) + strlen($start), (strlen($pubkeypem) - strpos($pubkeypem, $end)) * (-1)); $der = base64_decode($pemtrim); return hash('sha1', $der); } /** * Test if it is safe to use the PHP function openssl_x509_parse(). * * This checks if OpenSSL extensions is vulnerable to remote code execution * via the exploit documented as CVE-2013-6420. */ public static function isOpensslParseSafe(): bool { return CaBundle::isOpensslParseSafe(); } /** * Convert certificate name into matching function. * * @param string $certName CN/SAN */ private static function certNameMatcher(string $certName): ?callable { $wildcards = substr_count($certName, '*'); if (0 === $wildcards) { // Literal match. return static function ($hostname) use ($certName): bool { return $hostname === $certName; }; } if (1 === $wildcards) { $components = explode('.', $certName); if (3 > count($components)) { // Must have 3+ components return null; } $firstComponent = $components[0]; // Wildcard must be the last character. if ('*' !== $firstComponent[strlen($firstComponent) - 1]) { return null; } $wildcardRegex = preg_quote($certName); $wildcardRegex = str_replace('\\*', '[a-z0-9-]+', $wildcardRegex); $wildcardRegex = "{^{$wildcardRegex}$}"; return static function ($hostname) use ($wildcardRegex): bool { return Preg::isMatch($wildcardRegex, $hostname); }; } return null; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/ErrorHandler.php
src/Composer/Util/ErrorHandler.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\Util; use Composer\IO\IOInterface; /** * Convert PHP errors into exceptions * * @author Artem Lopata <biozshock@gmail.com> */ class ErrorHandler { /** @var ?IOInterface */ private static $io; /** @var int<0, 2> */ private static $hasShownDeprecationNotice = 0; /** * Error handler * * @param int $level Level of the error raised * @param string $message Error message * @param string $file Filename that the error was raised in * @param int $line Line number the error was raised at * * @static * @throws \ErrorException */ public static function handle(int $level, string $message, string $file, int $line): bool { $isDeprecationNotice = $level === E_DEPRECATED || $level === E_USER_DEPRECATED; // error code is not included in error_reporting if (!$isDeprecationNotice && 0 === (error_reporting() & $level)) { return true; } if (filter_var(ini_get('xdebug.scream'), FILTER_VALIDATE_BOOLEAN)) { $message .= "\n\nWarning: You have xdebug.scream enabled, the warning above may be". "\na legitimately suppressed error that you were not supposed to see."; } if (!$isDeprecationNotice) { // ignore some newly introduced warnings in new php versions until dependencies // can be fixed as we do not want to abort execution for those if (in_array($level, [E_WARNING, E_USER_WARNING], true) && str_contains($message, 'should either be used or intentionally ignored by casting it as (void)')) { self::outputWarning('Ignored new PHP warning but it should be reported and fixed: '.$message.' in '.$file.':'.$line, true); return true; } throw new \ErrorException($message, 0, $level, $file, $line); } if (self::$io !== null) { if (self::$hasShownDeprecationNotice > 0 && !self::$io->isVerbose()) { if (self::$hasShownDeprecationNotice === 1) { self::$io->writeError('<warning>More deprecation notices were hidden, run again with `-v` to show them.</warning>'); self::$hasShownDeprecationNotice = 2; } return true; } self::$hasShownDeprecationNotice = 1; self::outputWarning('Deprecation Notice: '.$message.' in '.$file.':'.$line); } return true; } /** * Register error handler. */ public static function register(?IOInterface $io = null): void { set_error_handler([__CLASS__, 'handle']); error_reporting(E_ALL); self::$io = $io; } private static function outputWarning(string $message, bool $outputEvenWithoutIO = false): void { if (self::$io !== null) { self::$io->writeError('<warning>'.$message.'</warning>'); if (self::$io->isVerbose()) { self::$io->writeError('<warning>Stack trace:</warning>'); self::$io->writeError(array_filter(array_map(static function ($a): ?string { if (isset($a['line'], $a['file'])) { return '<warning> '.$a['file'].':'.$a['line'].'</warning>'; } return null; }, array_slice(debug_backtrace(), 2)), static function (?string $line) { return $line !== null; })); } return; } if ($outputEvenWithoutIO) { if (defined('STDERR') && is_resource(STDERR)) { fwrite(STDERR, 'Warning: '.$message.PHP_EOL); } else { echo 'Warning: '.$message.PHP_EOL; } } } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Tar.php
src/Composer/Util/Tar.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\Util; /** * @author Wissem Riahi <wissemr@gmail.com> */ class Tar { public static function getComposerJson(string $pathToArchive): ?string { $phar = new \PharData($pathToArchive); if (!$phar->valid()) { return null; } return self::extractComposerJsonFromFolder($phar); } /** * @throws \RuntimeException */ private static function extractComposerJsonFromFolder(\PharData $phar): string { if (isset($phar['composer.json'])) { return $phar['composer.json']->getContent(); } $topLevelPaths = []; foreach ($phar as $folderFile) { $name = $folderFile->getBasename(); if ($folderFile->isDir()) { $topLevelPaths[$name] = true; if (\count($topLevelPaths) > 1) { throw new \RuntimeException('Archive has more than one top level directories, and no composer.json was found on the top level, so it\'s an invalid archive. Top level paths found were: '.implode(',', array_keys($topLevelPaths))); } } } $composerJsonPath = key($topLevelPaths).'/composer.json'; if (\count($topLevelPaths) > 0 && isset($phar[$composerJsonPath])) { return $phar[$composerJsonPath]->getContent(); } throw new \RuntimeException('No composer.json found either at the top level or within the topmost directory'); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Url.php
src/Composer/Util/Url.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\Util; use Composer\Config; use Composer\Pcre\Preg; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class Url { /** * @param non-empty-string $url * @return non-empty-string the updated URL */ public static function updateDistReference(Config $config, string $url, string $ref): string { $host = parse_url($url, PHP_URL_HOST); if ($host === 'api.github.com' || $host === 'github.com' || $host === 'www.github.com') { if (Preg::isMatch('{^https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/(zip|tar)ball/(.+)$}i', $url, $match)) { // update legacy github archives to API calls with the proper reference $url = 'https://api.github.com/repos/' . $match[1] . '/'. $match[2] . '/' . $match[3] . 'ball/' . $ref; } elseif (Preg::isMatch('{^https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/archive/.+\.(zip|tar)(?:\.gz)?$}i', $url, $match)) { // update current github web archives to API calls with the proper reference $url = 'https://api.github.com/repos/' . $match[1] . '/'. $match[2] . '/' . $match[3] . 'ball/' . $ref; } elseif (Preg::isMatch('{^https?://api\.github\.com/repos/([^/]+)/([^/]+)/(zip|tar)ball(?:/.+)?$}i', $url, $match)) { // update api archives to the proper reference $url = 'https://api.github.com/repos/' . $match[1] . '/'. $match[2] . '/' . $match[3] . 'ball/' . $ref; } } elseif ($host === 'bitbucket.org' || $host === 'www.bitbucket.org') { if (Preg::isMatch('{^https?://(?:www\.)?bitbucket\.org/([^/]+)/([^/]+)/get/(.+)\.(zip|tar\.gz|tar\.bz2)$}i', $url, $match)) { // update Bitbucket archives to the proper reference $url = 'https://bitbucket.org/' . $match[1] . '/'. $match[2] . '/get/' . $ref . '.' . $match[4]; } } elseif ($host === 'gitlab.com' || $host === 'www.gitlab.com') { if (Preg::isMatch('{^https?://(?:www\.)?gitlab\.com/api/v[34]/projects/([^/]+)/repository/archive\.(zip|tar\.gz|tar\.bz2|tar)\?sha=.+$}i', $url, $match)) { // update Gitlab archives to the proper reference $url = 'https://gitlab.com/api/v4/projects/' . $match[1] . '/repository/archive.' . $match[2] . '?sha=' . $ref; } } elseif (in_array($host, $config->get('github-domains'), true)) { $url = Preg::replace('{(/repos/[^/]+/[^/]+/(zip|tar)ball)(?:/.+)?$}i', '$1/'.$ref, $url); } elseif (in_array($host, $config->get('gitlab-domains'), true)) { $url = Preg::replace('{(/api/v[34]/projects/[^/]+/repository/archive\.(?:zip|tar\.gz|tar\.bz2|tar)\?sha=).+$}i', '${1}'.$ref, $url); } assert($url !== ''); return $url; } /** * @param non-empty-string $url * @return non-empty-string */ public static function getOrigin(Config $config, string $url): string { if (0 === strpos($url, 'file://')) { return $url; } $origin = (string) parse_url($url, PHP_URL_HOST); if ($port = parse_url($url, PHP_URL_PORT)) { $origin .= ':'.$port; } if (str_ends_with($origin, '.github.com') && $origin !== 'codeload.github.com') { return 'github.com'; } if ($origin === 'repo.packagist.org') { return 'packagist.org'; } if ($origin === '') { $origin = $url; } // Gitlab can be installed in a non-root context (i.e. gitlab.com/foo). When downloading archives the originUrl // is the host without the path, so we look for the registered gitlab-domains matching the host here if ( false === strpos($origin, '/') && !in_array($origin, $config->get('gitlab-domains'), true) ) { foreach ($config->get('gitlab-domains') as $gitlabDomain) { if ($gitlabDomain !== '' && str_starts_with($gitlabDomain, $origin)) { return $gitlabDomain; } } } return $origin; } public static function sanitize(string $url): string { // GitHub repository rename result in redirect locations containing the access_token as GET parameter // e.g. https://api.github.com/repositories/9999999999?access_token=github_token $url = Preg::replace('{([&?]access_token=)[^&]+}', '$1***', $url); $url = Preg::replaceCallback('{^(?P<prefix>[a-z0-9]+://)?(?P<user>[^:/\s@]+):(?P<password>[^@\s/]+)@}i', static function ($m): string { // if the username looks like a long (12char+) hex string, or a modern github token (e.g. ghp_xxx, github_pat_xxx) we obfuscate that if (Preg::isMatch(GitHub::GITHUB_TOKEN_REGEX, $m['user'])) { return $m['prefix'].'***:***@'; } return $m['prefix'].$m['user'].':***@'; }, $url); return $url; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/MetadataMinifier.php
src/Composer/Util/MetadataMinifier.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\Util; @trigger_error('Composer\Util\MetadataMinifier is deprecated, use Composer\MetadataMinifier\MetadataMinifier from composer/metadata-minifier instead.', E_USER_DEPRECATED); /** * @deprecated Use Composer\MetadataMinifier\MetadataMinifier instead */ class MetadataMinifier extends \Composer\MetadataMinifier\MetadataMinifier { }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/StreamContextFactory.php
src/Composer/Util/StreamContextFactory.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\Util; use Composer\Composer; use Composer\CaBundle\CaBundle; use Composer\Downloader\TransportException; use Composer\Repository\PlatformRepository; use Composer\Util\Http\ProxyManager; use Psr\Log\LoggerInterface; /** * Allows the creation of a basic context supporting http proxy * * @author Jordan Alliot <jordan.alliot@gmail.com> * @author Markus Tacker <m@coderbyheart.de> */ final class StreamContextFactory { /** * Creates a context supporting HTTP proxies * * @param non-empty-string $url URL the context is to be used for * @phpstan-param array{http?: array{follow_location?: int, max_redirects?: int, header?: string|array<string>}} $defaultOptions * @param mixed[] $defaultOptions Options to merge with the default * @param mixed[] $defaultParams Parameters to specify on the context * @throws \RuntimeException if https proxy required and OpenSSL uninstalled * @return resource Default context */ public static function getContext(string $url, array $defaultOptions = [], array $defaultParams = []) { $options = ['http' => [ // specify defaults again to try and work better with curlwrappers enabled 'follow_location' => 1, 'max_redirects' => 20, ]]; $options = array_replace_recursive($options, self::initOptions($url, $defaultOptions)); unset($defaultOptions['http']['header']); $options = array_replace_recursive($options, $defaultOptions); if (isset($options['http']['header'])) { $options['http']['header'] = self::fixHttpHeaderField($options['http']['header']); } return stream_context_create($options, $defaultParams); } /** * @param non-empty-string $url * @param mixed[] $options * @param bool $forCurl When true, will not add proxy values as these are handled separately * @phpstan-return array{http: array{header: string[], proxy?: string, request_fulluri: bool}, ssl?: mixed[]} * @return array formatted as a stream context array */ public static function initOptions(string $url, array $options, bool $forCurl = false): array { // Make sure the headers are in an array form if (!isset($options['http']['header'])) { $options['http']['header'] = []; } if (is_string($options['http']['header'])) { $options['http']['header'] = explode("\r\n", $options['http']['header']); } // Add stream proxy options if there is a proxy if (!$forCurl) { $proxy = ProxyManager::getInstance()->getProxyForRequest($url); $proxyOptions = $proxy->getContextOptions(); if ($proxyOptions !== null) { $isHttpsRequest = 0 === strpos($url, 'https://'); if ($proxy->isSecure()) { if (!extension_loaded('openssl')) { throw new TransportException('You must enable the openssl extension to use a secure proxy.'); } if ($isHttpsRequest) { throw new TransportException('You must enable the curl extension to make https requests through a secure proxy.'); } } elseif ($isHttpsRequest && !extension_loaded('openssl')) { throw new TransportException('You must enable the openssl extension to make https requests through a proxy.'); } // Header will be a Proxy-Authorization string or not set if (isset($proxyOptions['http']['header'])) { $options['http']['header'][] = $proxyOptions['http']['header']; unset($proxyOptions['http']['header']); } $options = array_replace_recursive($options, $proxyOptions); } } if (defined('HHVM_VERSION')) { $phpVersion = 'HHVM ' . HHVM_VERSION; } else { $phpVersion = 'PHP ' . PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION; } if ($forCurl) { $curl = curl_version(); $httpVersion = 'cURL '.$curl['version']; } else { $httpVersion = 'streams'; } if (!isset($options['http']['header']) || false === stripos(implode('', $options['http']['header']), 'user-agent')) { $platformPhpVersion = PlatformRepository::getPlatformPhpVersion(); $options['http']['header'][] = sprintf( 'User-Agent: Composer/%s (%s; %s; %s; %s%s%s)', Composer::getVersion(), function_exists('php_uname') ? php_uname('s') : 'Unknown', function_exists('php_uname') ? php_uname('r') : 'Unknown', $phpVersion, $httpVersion, $platformPhpVersion ? '; Platform-PHP '.$platformPhpVersion : '', Platform::getEnv('CI') ? '; CI' : '' ); } return $options; } /** * @param mixed[] $options * * @return mixed[] */ public static function getTlsDefaults(array $options, ?LoggerInterface $logger = null): array { $ciphers = implode(':', [ 'ECDHE-RSA-AES128-GCM-SHA256', 'ECDHE-ECDSA-AES128-GCM-SHA256', 'ECDHE-RSA-AES256-GCM-SHA384', 'ECDHE-ECDSA-AES256-GCM-SHA384', 'DHE-RSA-AES128-GCM-SHA256', 'DHE-DSS-AES128-GCM-SHA256', 'kEDH+AESGCM', 'ECDHE-RSA-AES128-SHA256', 'ECDHE-ECDSA-AES128-SHA256', 'ECDHE-RSA-AES128-SHA', 'ECDHE-ECDSA-AES128-SHA', 'ECDHE-RSA-AES256-SHA384', 'ECDHE-ECDSA-AES256-SHA384', 'ECDHE-RSA-AES256-SHA', 'ECDHE-ECDSA-AES256-SHA', 'DHE-RSA-AES128-SHA256', 'DHE-RSA-AES128-SHA', 'DHE-DSS-AES128-SHA256', 'DHE-RSA-AES256-SHA256', 'DHE-DSS-AES256-SHA', 'DHE-RSA-AES256-SHA', 'AES128-GCM-SHA256', 'AES256-GCM-SHA384', 'AES128-SHA256', 'AES256-SHA256', 'AES128-SHA', 'AES256-SHA', 'AES', 'CAMELLIA', 'DES-CBC3-SHA', '!aNULL', '!eNULL', '!EXPORT', '!DES', '!RC4', '!MD5', '!PSK', '!aECDH', '!EDH-DSS-DES-CBC3-SHA', '!EDH-RSA-DES-CBC3-SHA', '!KRB5-DES-CBC3-SHA', ]); /** * CN_match and SNI_server_name are only known once a URL is passed. * They will be set in the getOptionsForUrl() method which receives a URL. * * cafile or capath can be overridden by passing in those options to constructor. */ $defaults = [ 'ssl' => [ 'ciphers' => $ciphers, 'verify_peer' => true, 'verify_depth' => 7, 'SNI_enabled' => true, 'capture_peer_cert' => true, ], ]; if (isset($options['ssl'])) { $defaults['ssl'] = array_replace_recursive($defaults['ssl'], $options['ssl']); } /** * Attempt to find a local cafile or throw an exception if none pre-set * The user may go download one if this occurs. */ if (!isset($defaults['ssl']['cafile']) && !isset($defaults['ssl']['capath'])) { $result = CaBundle::getSystemCaRootBundlePath($logger); if (is_dir($result)) { $defaults['ssl']['capath'] = $result; } else { $defaults['ssl']['cafile'] = $result; } } if (isset($defaults['ssl']['cafile']) && (!Filesystem::isReadable($defaults['ssl']['cafile']) || !CaBundle::validateCaFile($defaults['ssl']['cafile'], $logger))) { throw new TransportException('The configured cafile was not valid or could not be read.'); } if (isset($defaults['ssl']['capath']) && (!is_dir($defaults['ssl']['capath']) || !Filesystem::isReadable($defaults['ssl']['capath']))) { throw new TransportException('The configured capath was not valid or could not be read.'); } /** * Disable TLS compression to prevent CRIME attacks where supported. */ $defaults['ssl']['disable_compression'] = true; return $defaults; } /** * A bug in PHP prevents the headers from correctly being sent when a content-type header is present and * NOT at the end of the array * * This method fixes the array by moving the content-type header to the end * * @link https://bugs.php.net/bug.php?id=61548 * @param string|string[] $header * @return string[] */ private static function fixHttpHeaderField($header): array { if (!is_array($header)) { $header = explode("\r\n", $header); } uasort($header, static function ($el): int { return stripos($el, 'content-type') === 0 ? 1 : -1; }); return $header; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/ProcessExecutor.php
src/Composer/Util/ProcessExecutor.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\Util; use Composer\IO\IOInterface; use Composer\Pcre\Preg; use Seld\Signal\SignalHandler; use Symfony\Component\Process\Exception\ProcessSignaledException; use Symfony\Component\Process\Process; use Symfony\Component\Process\Exception\RuntimeException; use React\Promise\Promise; use React\Promise\PromiseInterface; use Symfony\Component\Process\ExecutableFinder; /** * @author Robert Schönthal <seroscho@googlemail.com> * @author Jordi Boggiano <j.boggiano@seld.be> */ class ProcessExecutor { private const STATUS_QUEUED = 1; private const STATUS_STARTED = 2; private const STATUS_COMPLETED = 3; private const STATUS_FAILED = 4; private const STATUS_ABORTED = 5; private const BUILTIN_CMD_COMMANDS = [ 'assoc', 'break', 'call', 'cd', 'chdir', 'cls', 'color', 'copy', 'date', 'del', 'dir', 'echo', 'endlocal', 'erase', 'exit', 'for', 'ftype', 'goto', 'help', 'if', 'label', 'md', 'mkdir', 'mklink', 'move', 'path', 'pause', 'popd', 'prompt', 'pushd', 'rd', 'rem', 'ren', 'rename', 'rmdir', 'set', 'setlocal', 'shift', 'start', 'time', 'title', 'type', 'ver', 'vol', ]; private const GIT_CMDS_NEED_GIT_DIR = [ ['show'], ['log'], ['branch'], ['remote', 'set-url'], ]; /** @var int */ protected static $timeout = 300; /** @var bool */ protected $captureOutput = false; /** @var string */ protected $errorOutput = ''; /** @var ?IOInterface */ protected $io; /** * @phpstan-var array<int, array<string, mixed>> */ private $jobs = []; /** @var int */ private $runningJobs = 0; /** @var int */ private $maxJobs = 10; /** @var int */ private $idGen = 0; /** @var bool */ private $allowAsync = false; /** @var array<string, string> */ private static $executables = []; public function __construct(?IOInterface $io = null) { $this->io = $io; $this->resetMaxJobs(); } /** * runs a process on the commandline * * @param string|non-empty-list<string> $command the command to execute * @param mixed $output the output will be written into this var if passed by ref * if a callable is passed it will be used as output handler * @param null|string $cwd the working directory * @return int statuscode */ public function execute($command, &$output = null, ?string $cwd = null): int { if (func_num_args() > 1) { return $this->doExecute($command, $cwd, false, $output); } return $this->doExecute($command, $cwd, false); } /** * runs a process on the commandline in TTY mode * * @param string|non-empty-list<string> $command the command to execute * @param null|string $cwd the working directory * @return int statuscode */ public function executeTty($command, ?string $cwd = null): int { if (Platform::isTty()) { return $this->doExecute($command, $cwd, true); } return $this->doExecute($command, $cwd, false); } /** * @param string|non-empty-list<string> $command * @param array<string, string>|null $env * @param mixed $output */ private function runProcess($command, ?string $cwd, ?array $env, bool $tty, &$output = null): ?int { // On Windows, we don't rely on the OS to find the executable if possible to avoid lookups // in the current directory which could be untrusted. Instead we use the ExecutableFinder. if (is_string($command)) { if (Platform::isWindows() && Preg::isMatch('{^([^:/\\\\]++) }', $command, $match)) { $command = substr_replace($command, self::escape(self::getExecutable($match[1])), 0, strlen($match[1])); } $process = Process::fromShellCommandline($command, $cwd, $env, null, static::getTimeout()); } else { if (Platform::isWindows() && \strlen($command[0]) === strcspn($command[0], ':/\\')) { $command[0] = self::getExecutable($command[0]); } $process = new Process($command, $cwd, $env, null, static::getTimeout()); } if (!Platform::isWindows() && $tty) { try { $process->setTty(true); } catch (RuntimeException $e) { // ignore TTY enabling errors } } $callback = is_callable($output) ? $output : function (string $type, string $buffer): void { $this->outputHandler($type, $buffer); }; $signalHandler = SignalHandler::create( [SignalHandler::SIGINT, SignalHandler::SIGTERM, SignalHandler::SIGHUP], function (string $signal) { if ($this->io !== null) { $this->io->writeError( 'Received '.$signal.', aborting when child process is done', true, IOInterface::DEBUG ); } } ); try { $process->run($callback); if ($this->captureOutput && !is_callable($output)) { $output = $process->getOutput(); } $this->errorOutput = $process->getErrorOutput(); } catch (ProcessSignaledException $e) { if ($signalHandler->isTriggered()) { // exiting as we were signaled and the child process exited too due to the signal $signalHandler->exitWithLastSignal(); } } finally { $signalHandler->unregister(); } return $process->getExitCode(); } /** * @param string|non-empty-list<string> $command * @param mixed $output */ private function doExecute($command, ?string $cwd, bool $tty, &$output = null): int { $this->outputCommandRun($command, $cwd, false); $this->captureOutput = func_num_args() > 3; $this->errorOutput = ''; $env = null; $requiresGitDirEnv = $this->requiresGitDirEnv($command); if ($cwd !== null && $requiresGitDirEnv) { $isBareRepository = !is_dir(sprintf('%s/.git', rtrim($cwd, '/'))); if ($isBareRepository) { $configValue = ''; $this->runProcess(['git', 'config', 'safe.bareRepository'], $cwd, ['GIT_DIR' => $cwd], $tty, $configValue); $configValue = trim($configValue); if ($configValue === 'explicit') { $env = ['GIT_DIR' => $cwd]; } } } return $this->runProcess($command, $cwd, $env, $tty, $output); } /** * starts a process on the commandline in async mode * * @param string|list<string> $command the command to execute * @param string $cwd the working directory * @phpstan-return PromiseInterface<Process> */ public function executeAsync($command, ?string $cwd = null): PromiseInterface { if (!$this->allowAsync) { throw new \LogicException('You must use the ProcessExecutor instance which is part of a Composer\Loop instance to be able to run async processes'); } $job = [ 'id' => $this->idGen++, 'status' => self::STATUS_QUEUED, 'command' => $command, 'cwd' => $cwd, ]; $resolver = static function ($resolve, $reject) use (&$job): void { $job['status'] = ProcessExecutor::STATUS_QUEUED; $job['resolve'] = $resolve; $job['reject'] = $reject; }; $canceler = static function () use (&$job): void { if ($job['status'] === ProcessExecutor::STATUS_QUEUED) { $job['status'] = ProcessExecutor::STATUS_ABORTED; } if ($job['status'] !== ProcessExecutor::STATUS_STARTED) { return; } $job['status'] = ProcessExecutor::STATUS_ABORTED; try { if (defined('SIGINT')) { $job['process']->signal(SIGINT); } } catch (\Exception $e) { // signal can throw in various conditions, but we don't care if it fails } $job['process']->stop(1); throw new \RuntimeException('Aborted process'); }; $promise = new Promise($resolver, $canceler); $promise = $promise->then(function () use (&$job) { if ($job['process']->isSuccessful()) { $job['status'] = ProcessExecutor::STATUS_COMPLETED; } else { $job['status'] = ProcessExecutor::STATUS_FAILED; } $this->markJobDone(); return $job['process']; }, function ($e) use (&$job): void { $job['status'] = ProcessExecutor::STATUS_FAILED; $this->markJobDone(); throw $e; }); $this->jobs[$job['id']] = &$job; if ($this->runningJobs < $this->maxJobs) { $this->startJob($job['id']); } return $promise; } protected function outputHandler(string $type, string $buffer): void { if ($this->captureOutput) { return; } if (null === $this->io) { echo $buffer; return; } if (Process::ERR === $type) { $this->io->writeErrorRaw($buffer, false); } else { $this->io->writeRaw($buffer, false); } } private function startJob(int $id): void { $job = &$this->jobs[$id]; if ($job['status'] !== self::STATUS_QUEUED) { return; } // start job $job['status'] = self::STATUS_STARTED; $this->runningJobs++; $command = $job['command']; $cwd = $job['cwd']; $this->outputCommandRun($command, $cwd, true); try { if (is_string($command)) { $process = Process::fromShellCommandline($command, $cwd, null, null, static::getTimeout()); } else { $process = new Process($command, $cwd, null, null, static::getTimeout()); } } catch (\Throwable $e) { $job['reject']($e); return; } $job['process'] = $process; try { $process->start(); } catch (\Throwable $e) { $job['reject']($e); return; } } public function setMaxJobs(int $maxJobs): void { $this->maxJobs = $maxJobs; } public function resetMaxJobs(): void { if (is_numeric($maxJobs = Platform::getEnv('COMPOSER_MAX_PARALLEL_PROCESSES'))) { $this->maxJobs = max(1, min(50, (int) $maxJobs)); } else { $this->maxJobs = 10; } } /** * @param ?int $index job id */ public function wait($index = null): void { while (true) { if (0 === $this->countActiveJobs($index)) { return; } usleep(1000); } } /** * @internal */ public function enableAsync(): void { $this->allowAsync = true; } /** * @internal * * @param ?int $index job id * @return int number of active (queued or started) jobs */ public function countActiveJobs($index = null): int { // tick foreach ($this->jobs as $job) { if ($job['status'] === self::STATUS_STARTED) { if (!$job['process']->isRunning()) { call_user_func($job['resolve'], $job['process']); } $job['process']->checkTimeout(); } if ($this->runningJobs < $this->maxJobs) { if ($job['status'] === self::STATUS_QUEUED) { $this->startJob($job['id']); } } } if (null !== $index) { return $this->jobs[$index]['status'] < self::STATUS_COMPLETED ? 1 : 0; } $active = 0; foreach ($this->jobs as $job) { if ($job['status'] < self::STATUS_COMPLETED) { $active++; } else { unset($this->jobs[$job['id']]); } } return $active; } private function markJobDone(): void { $this->runningJobs--; } /** * @return string[] */ public function splitLines(?string $output): array { $output = trim((string) $output); return $output === '' ? [] : Preg::split('{\r?\n}', $output); } /** * Get any error output from the last command */ public function getErrorOutput(): string { return $this->errorOutput; } /** * @return int the timeout in seconds */ public static function getTimeout(): int { return static::$timeout; } /** * @param int $timeout the timeout in seconds */ public static function setTimeout(int $timeout): void { static::$timeout = $timeout; } /** * Escapes a string to be used as a shell argument. * * @param string|false|null $argument The argument that will be escaped * * @return string The escaped argument */ public static function escape($argument): string { return self::escapeArgument($argument); } /** * @param string|list<string> $command */ private function outputCommandRun($command, ?string $cwd, bool $async): void { if (null === $this->io || !$this->io->isDebug()) { return; } $commandString = is_string($command) ? $command : implode(' ', array_map(self::class.'::escape', $command)); $safeCommand = Preg::replaceCallback('{://(?P<user>[^:/\s]+):(?P<password>[^@\s/]+)@}i', static function ($m): string { // if the username looks like a long (12char+) hex string, or a modern github token (e.g. ghp_xxx, github_pat_xxx) we obfuscate that if (Preg::isMatch(GitHub::GITHUB_TOKEN_REGEX, $m['user'])) { return '://***:***@'; } if (Preg::isMatch('{^[a-f0-9]{12,}$}', $m['user'])) { return '://***:***@'; } return '://'.$m['user'].':***@'; }, $commandString); $safeCommand = Preg::replace("{--password (.*[^\\\\]\') }", '--password \'***\' ', $safeCommand); $this->io->writeError('Executing'.($async ? ' async' : '').' command ('.($cwd ?: 'CWD').'): '.$safeCommand); } /** * Escapes a string to be used as a shell argument for Symfony Process. * * This method expects cmd.exe to be started with the /V:ON option, which * enables delayed environment variable expansion using ! as the delimiter. * If this is not the case, any escaped ^^!var^^! will be transformed to * ^!var^! and introduce two unintended carets. * * Modified from https://github.com/johnstevenson/winbox-args * MIT Licensed (c) John Stevenson <john-stevenson@blueyonder.co.uk> * * @param string|false|null $argument */ private static function escapeArgument($argument): string { if ('' === ($argument = (string) $argument)) { return escapeshellarg($argument); } if (!Platform::isWindows()) { return "'".str_replace("'", "'\\''", $argument)."'"; } // New lines break cmd.exe command parsing // and special chars like the fullwidth quote can be used to break out // of parameter encoding via "Best Fit" encoding conversion $argument = strtr($argument, [ "\n" => ' ', "\u{ff02}" => '"', "\u{02ba}" => '"', "\u{301d}" => '"', "\u{301e}" => '"', "\u{030e}" => '"', "\u{ff1a}" => ':', "\u{0589}" => ':', "\u{2236}" => ':', "\u{ff0f}" => '/', "\u{2044}" => '/', "\u{2215}" => '/', "\u{00b4}" => '/', ]); // In addition to whitespace, commas need quoting to preserve paths $quote = strpbrk($argument, " \t,") !== false; $argument = Preg::replace('/(\\\\*)"/', '$1$1\\"', $argument, -1, $dquotes); $meta = $dquotes > 0 || Preg::isMatch('/%[^%]+%|![^!]+!/', $argument); if (!$meta && !$quote) { $quote = strpbrk($argument, '^&|<>()') !== false; } if ($quote) { $argument = '"'.Preg::replace('/(\\\\*)$/', '$1$1', $argument).'"'; } if ($meta) { $argument = Preg::replace('/(["^&|<>()%])/', '^$1', $argument); $argument = Preg::replace('/(!)/', '^^$1', $argument); } return $argument; } /** * @param string[]|string $command */ public function requiresGitDirEnv($command): bool { $cmd = !is_array($command) ? explode(' ', $command) : $command; if ($cmd[0] !== 'git') { return false; } foreach (self::GIT_CMDS_NEED_GIT_DIR as $gitCmd) { if (array_intersect($cmd, $gitCmd) === $gitCmd) { return true; } } return false; } /** * Resolves executable paths on Windows */ private static function getExecutable(string $name): string { if (\in_array(strtolower($name), self::BUILTIN_CMD_COMMANDS, true)) { return $name; } if (!isset(self::$executables[$name])) { $path = (new ExecutableFinder())->find($name, $name); if ($path !== null) { self::$executables[$name] = $path; } } return self::$executables[$name] ?? $name; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Loop.php
src/Composer/Util/Loop.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\Util; use Symfony\Component\Console\Helper\ProgressBar; use React\Promise\PromiseInterface; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class Loop { /** @var HttpDownloader */ private $httpDownloader; /** @var ProcessExecutor|null */ private $processExecutor; /** @var array<int, array<PromiseInterface<mixed>>> */ private $currentPromises = []; /** @var int */ private $waitIndex = 0; public function __construct(HttpDownloader $httpDownloader, ?ProcessExecutor $processExecutor = null) { $this->httpDownloader = $httpDownloader; $this->httpDownloader->enableAsync(); $this->processExecutor = $processExecutor; if ($this->processExecutor) { $this->processExecutor->enableAsync(); } } public function getHttpDownloader(): HttpDownloader { return $this->httpDownloader; } public function getProcessExecutor(): ?ProcessExecutor { return $this->processExecutor; } /** * @param array<PromiseInterface<mixed>> $promises */ public function wait(array $promises, ?ProgressBar $progress = null): void { $uncaught = null; \React\Promise\all($promises)->then( static function (): void { }, static function (\Throwable $e) use (&$uncaught): void { $uncaught = $e; } ); // keep track of every group of promises that is waited on, so abortJobs can // cancel them all, even if wait() was called within a wait() $waitIndex = $this->waitIndex++; $this->currentPromises[$waitIndex] = $promises; if ($progress) { $totalJobs = 0; $totalJobs += $this->httpDownloader->countActiveJobs(); if ($this->processExecutor) { $totalJobs += $this->processExecutor->countActiveJobs(); } $progress->start($totalJobs); } $lastUpdate = 0; while (true) { $activeJobs = 0; $activeJobs += $this->httpDownloader->countActiveJobs(); if ($this->processExecutor) { $activeJobs += $this->processExecutor->countActiveJobs(); } if ($progress && microtime(true) - $lastUpdate > 0.1) { $lastUpdate = microtime(true); $progress->setProgress($progress->getMaxSteps() - $activeJobs); } if (!$activeJobs) { break; } } // as we skip progress updates if they are too quick, make sure we do one last one here at 100% if ($progress) { $progress->finish(); } unset($this->currentPromises[$waitIndex]); if (null !== $uncaught) { throw $uncaught; } } public function abortJobs(): void { foreach ($this->currentPromises as $promiseGroup) { foreach ($promiseGroup as $promise) { // to support react/promise 2.x we wrap the promise in a resolve() call for safety \React\Promise\resolve($promise)->cancel(); } } } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/ComposerMirror.php
src/Composer/Util/ComposerMirror.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\Util; use Composer\Pcre\Preg; /** * Composer mirror utilities * * @author Jordi Boggiano <j.boggiano@seld.be> */ class ComposerMirror { /** * @param non-empty-string $mirrorUrl * @return non-empty-string */ public static function processUrl(string $mirrorUrl, string $packageName, string $version, ?string $reference, ?string $type, ?string $prettyVersion = null): string { if ($reference) { $reference = Preg::isMatch('{^([a-f0-9]*|%reference%)$}', $reference) ? $reference : hash('md5', $reference); } $version = strpos($version, '/') === false ? $version : hash('md5', $version); $from = ['%package%', '%version%', '%reference%', '%type%']; $to = [$packageName, $version, $reference, $type]; if (null !== $prettyVersion) { $from[] = '%prettyVersion%'; $to[] = $prettyVersion; } $url = str_replace($from, $to, $mirrorUrl); assert($url !== ''); return $url; } /** * @param non-empty-string $mirrorUrl */ public static function processGitUrl(string $mirrorUrl, string $packageName, string $url, ?string $type): string { if (Preg::isMatch('#^(?:(?:https?|git)://github\.com/|git@github\.com:)([^/]+)/(.+?)(?:\.git)?$#', $url, $match)) { $url = 'gh-'.$match[1].'/'.$match[2]; } elseif (Preg::isMatch('#^https://bitbucket\.org/([^/]+)/(.+?)(?:\.git)?/?$#', $url, $match)) { $url = 'bb-'.$match[1].'/'.$match[2]; } else { $url = Preg::replace('{[^a-z0-9_.-]}i', '-', trim($url, '/')); } return str_replace( ['%package%', '%normalizedUrl%', '%type%'], [$packageName, $url, $type], $mirrorUrl ); } /** * @param non-empty-string $mirrorUrl */ public static function processHgUrl(string $mirrorUrl, string $packageName, string $url, string $type): string { return self::processGitUrl($mirrorUrl, $packageName, $url, $type); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Perforce.php
src/Composer/Util/Perforce.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\Util; use Composer\IO\IOInterface; use Composer\Pcre\Preg; use Symfony\Component\Process\ExecutableFinder; use Symfony\Component\Process\Process; /** * @author Matt Whittom <Matt.Whittom@veteransunited.com> * * @phpstan-type RepoConfig array{unique_perforce_client_name?: string, depot?: string, branch?: string, p4user?: string, p4password?: string} */ class Perforce { /** @var string */ protected $path; /** @var ?string */ protected $p4Depot; /** @var ?string */ protected $p4Client; /** @var ?string */ protected $p4User; /** @var ?string */ protected $p4Password; /** @var string */ protected $p4Port; /** @var ?string */ protected $p4Stream; /** @var string */ protected $p4ClientSpec; /** @var ?string */ protected $p4DepotType; /** @var ?string */ protected $p4Branch; /** @var ProcessExecutor */ protected $process; /** @var string */ protected $uniquePerforceClientName; /** @var bool */ protected $windowsFlag; /** @var string */ protected $commandResult; /** @var IOInterface */ protected $io; /** @var ?Filesystem */ protected $filesystem; /** * @phpstan-param RepoConfig $repoConfig */ public function __construct($repoConfig, string $port, string $path, ProcessExecutor $process, bool $isWindows, IOInterface $io) { $this->windowsFlag = $isWindows; $this->p4Port = $port; $this->initializePath($path); $this->process = $process; $this->initialize($repoConfig); $this->io = $io; } /** * @phpstan-param RepoConfig $repoConfig */ public static function create($repoConfig, string $port, string $path, ProcessExecutor $process, IOInterface $io): self { return new Perforce($repoConfig, $port, $path, $process, Platform::isWindows(), $io); } public static function checkServerExists(string $url, ProcessExecutor $processExecutor): bool { return 0 === $processExecutor->execute(['p4', '-p', $url, 'info', '-s'], $ignoredOutput); } /** * @phpstan-param RepoConfig $repoConfig */ public function initialize($repoConfig): void { $this->uniquePerforceClientName = $this->generateUniquePerforceClientName(); if (!$repoConfig) { return; } if (isset($repoConfig['unique_perforce_client_name'])) { $this->uniquePerforceClientName = $repoConfig['unique_perforce_client_name']; } if (isset($repoConfig['depot'])) { $this->p4Depot = $repoConfig['depot']; } if (isset($repoConfig['branch'])) { $this->p4Branch = $repoConfig['branch']; } if (isset($repoConfig['p4user'])) { $this->p4User = $repoConfig['p4user']; } else { $this->p4User = $this->getP4variable('P4USER'); } if (isset($repoConfig['p4password'])) { $this->p4Password = $repoConfig['p4password']; } } public function initializeDepotAndBranch(?string $depot, ?string $branch): void { if (isset($depot)) { $this->p4Depot = $depot; } if (isset($branch)) { $this->p4Branch = $branch; } } /** * @return non-empty-string */ public function generateUniquePerforceClientName(): string { return gethostname() . "_" . time(); } public function cleanupClientSpec(): void { $client = $this->getClient(); $task = 'client -d ' . ProcessExecutor::escape($client); $useP4Client = false; $command = $this->generateP4Command($task, $useP4Client); $this->executeCommand($command); $clientSpec = $this->getP4ClientSpec(); $fileSystem = $this->getFilesystem(); $fileSystem->remove($clientSpec); } /** * @param non-empty-string $command */ protected function executeCommand($command): int { $this->commandResult = ''; return $this->process->execute($command, $this->commandResult); } public function getClient(): string { if (!isset($this->p4Client)) { $cleanStreamName = str_replace(['//', '/', '@'], ['', '_', ''], $this->getStream()); $this->p4Client = 'composer_perforce_' . $this->uniquePerforceClientName . '_' . $cleanStreamName; } return $this->p4Client; } protected function getPath(): string { return $this->path; } public function initializePath(string $path): void { $this->path = $path; $fs = $this->getFilesystem(); $fs->ensureDirectoryExists($path); } protected function getPort(): string { return $this->p4Port; } public function setStream(string $stream): void { $this->p4Stream = $stream; $index = strrpos($stream, '/'); //Stream format is //depot/stream, while non-streaming depot is //depot if ($index > 2) { $this->p4DepotType = 'stream'; } } public function isStream(): bool { return is_string($this->p4DepotType) && (strcmp($this->p4DepotType, 'stream') === 0); } public function getStream(): string { if (!isset($this->p4Stream)) { if ($this->isStream()) { $this->p4Stream = '//' . $this->p4Depot . '/' . $this->p4Branch; } else { $this->p4Stream = '//' . $this->p4Depot; } } return $this->p4Stream; } public function getStreamWithoutLabel(string $stream): string { $index = strpos($stream, '@'); if ($index === false) { return $stream; } return substr($stream, 0, $index); } /** * @return non-empty-string */ public function getP4ClientSpec(): string { return $this->path . '/' . $this->getClient() . '.p4.spec'; } public function getUser(): ?string { return $this->p4User; } public function setUser(?string $user): void { $this->p4User = $user; } public function queryP4User(): void { $this->getUser(); if (strlen((string) $this->p4User) > 0) { return; } $this->p4User = $this->getP4variable('P4USER'); if (strlen((string) $this->p4User) > 0) { return; } $this->p4User = $this->io->ask('Enter P4 User:'); if ($this->windowsFlag) { $command = $this->getP4Executable().' set P4USER=' . $this->p4User; } else { $command = 'export P4USER=' . $this->p4User; } $this->executeCommand($command); } protected function getP4variable(string $name): ?string { if ($this->windowsFlag) { $command = $this->getP4Executable().' set'; $this->executeCommand($command); $result = trim($this->commandResult); $resArray = explode(PHP_EOL, $result); foreach ($resArray as $line) { $fields = explode('=', $line); if (strcmp($name, $fields[0]) === 0) { $index = strpos($fields[1], ' '); if ($index === false) { $value = $fields[1]; } else { $value = substr($fields[1], 0, $index); } $value = trim($value); return $value; } } return null; } $command = 'echo $' . $name; $this->executeCommand($command); $result = trim($this->commandResult); return $result; } public function queryP4Password(): ?string { if (isset($this->p4Password)) { return $this->p4Password; } $password = $this->getP4variable('P4PASSWD'); if (strlen((string) $password) <= 0) { $password = $this->io->askAndHideAnswer('Enter password for Perforce user ' . $this->getUser() . ': '); } $this->p4Password = $password; return $password; } /** * @return non-empty-string */ public function generateP4Command(string $command, bool $useClient = true): string { $p4Command = $this->getP4Executable().' '; $p4Command .= '-u ' . $this->getUser() . ' '; if ($useClient) { $p4Command .= '-c ' . $this->getClient() . ' '; } $p4Command .= '-p ' . $this->getPort() . ' ' . $command; return $p4Command; } public function isLoggedIn(): bool { $command = $this->generateP4Command('login -s', false); $exitCode = $this->executeCommand($command); if ($exitCode) { $errorOutput = $this->process->getErrorOutput(); $index = strpos($errorOutput, $this->getUser()); if ($index === false) { $index = strpos($errorOutput, 'p4'); if ($index === false) { return false; } throw new \Exception('p4 command not found in path: ' . $errorOutput); } throw new \Exception('Invalid user name: ' . $this->getUser()); } return true; } public function connectClient(): void { $p4CreateClientCommand = $this->generateP4Command( 'client -i < ' . ProcessExecutor::escape($this->getP4ClientSpec()) ); $this->executeCommand($p4CreateClientCommand); } public function syncCodeBase(?string $sourceReference): void { $prevDir = Platform::getCwd(); chdir($this->path); $p4SyncCommand = $this->generateP4Command('sync -f '); if (null !== $sourceReference) { $p4SyncCommand .= '@' . $sourceReference; } $this->executeCommand($p4SyncCommand); chdir($prevDir); } /** * @param resource|false $spec */ public function writeClientSpecToFile($spec): void { fwrite($spec, 'Client: ' . $this->getClient() . PHP_EOL . PHP_EOL); fwrite($spec, 'Update: ' . date('Y/m/d H:i:s') . PHP_EOL . PHP_EOL); fwrite($spec, 'Access: ' . date('Y/m/d H:i:s') . PHP_EOL); fwrite($spec, 'Owner: ' . $this->getUser() . PHP_EOL . PHP_EOL); fwrite($spec, 'Description:' . PHP_EOL); fwrite($spec, ' Created by ' . $this->getUser() . ' from composer.' . PHP_EOL . PHP_EOL); fwrite($spec, 'Root: ' . $this->getPath() . PHP_EOL . PHP_EOL); fwrite($spec, 'Options: noallwrite noclobber nocompress unlocked modtime rmdir' . PHP_EOL . PHP_EOL); fwrite($spec, 'SubmitOptions: revertunchanged' . PHP_EOL . PHP_EOL); fwrite($spec, 'LineEnd: local' . PHP_EOL . PHP_EOL); if ($this->isStream()) { fwrite($spec, 'Stream:' . PHP_EOL); fwrite($spec, ' ' . $this->getStreamWithoutLabel($this->p4Stream) . PHP_EOL); } else { fwrite( $spec, 'View: ' . $this->getStream() . '/... //' . $this->getClient() . '/... ' . PHP_EOL ); } } public function writeP4ClientSpec(): void { $clientSpec = $this->getP4ClientSpec(); $spec = fopen($clientSpec, 'w'); try { $this->writeClientSpecToFile($spec); } catch (\Exception $e) { fclose($spec); throw $e; } fclose($spec); } /** * @param resource $pipe * @param mixed $name */ protected function read($pipe, $name): void { if (feof($pipe)) { return; } $line = fgets($pipe); while ($line !== false) { $line = fgets($pipe); } } public function windowsLogin(?string $password): int { $command = $this->generateP4Command(' login -a'); $process = Process::fromShellCommandline($command, null, null, $password); return $process->run(); } public function p4Login(): void { $this->queryP4User(); if (!$this->isLoggedIn()) { $password = $this->queryP4Password(); if ($this->windowsFlag) { $this->windowsLogin($password); } else { $command = 'echo ' . ProcessExecutor::escape($password) . ' | ' . $this->generateP4Command(' login -a', false); $exitCode = $this->executeCommand($command); if ($exitCode) { throw new \Exception("Error logging in:" . $this->process->getErrorOutput()); } } } } /** * @return mixed[]|null */ public function getComposerInformation(string $identifier): ?array { $composerFileContent = $this->getFileContent('composer.json', $identifier); if (!$composerFileContent) { return null; } return json_decode($composerFileContent, true); } public function getFileContent(string $file, string $identifier): ?string { $path = $this->getFilePath($file, $identifier); $command = $this->generateP4Command(' print ' . ProcessExecutor::escape($path)); $this->executeCommand($command); $result = $this->commandResult; if (!trim($result)) { return null; } return $result; } public function getFilePath(string $file, string $identifier): ?string { $index = strpos($identifier, '@'); if ($index === false) { return $identifier. '/' . $file; } $path = substr($identifier, 0, $index) . '/' . $file . substr($identifier, $index); $command = $this->generateP4Command(' files ' . ProcessExecutor::escape($path), false); $this->executeCommand($command); $result = $this->commandResult; $index2 = strpos($result, 'no such file(s).'); if ($index2 === false) { $index3 = strpos($result, 'change'); if ($index3 !== false) { $phrase = trim(substr($result, $index3)); $fields = explode(' ', $phrase); return substr($identifier, 0, $index) . '/' . $file . '@' . $fields[1]; } } return null; } /** * @return array{master: string} */ public function getBranches(): array { $possibleBranches = []; if (!$this->isStream()) { $possibleBranches[$this->p4Branch] = $this->getStream(); } else { $command = $this->generateP4Command('streams '.ProcessExecutor::escape('//' . $this->p4Depot . '/...')); $this->executeCommand($command); $result = $this->commandResult; $resArray = explode(PHP_EOL, $result); foreach ($resArray as $line) { $resBits = explode(' ', $line); if (count($resBits) > 4) { $branch = Preg::replace('/[^A-Za-z0-9 ]/', '', $resBits[4]); $possibleBranches[$branch] = $resBits[1]; } } } $command = $this->generateP4Command('changes '. ProcessExecutor::escape($this->getStream() . '/...'), false); $this->executeCommand($command); $result = $this->commandResult; $resArray = explode(PHP_EOL, $result); $lastCommit = $resArray[0]; $lastCommitArr = explode(' ', $lastCommit); $lastCommitNum = $lastCommitArr[1]; return ['master' => $possibleBranches[$this->p4Branch] . '@'. $lastCommitNum]; } /** * @return array<string, string> */ public function getTags(): array { $command = $this->generateP4Command('labels'); $this->executeCommand($command); $result = $this->commandResult; $resArray = explode(PHP_EOL, $result); $tags = []; foreach ($resArray as $line) { if (strpos($line, 'Label') !== false) { $fields = explode(' ', $line); $tags[$fields[1]] = $this->getStream() . '@' . $fields[1]; } } return $tags; } public function checkStream(): bool { $command = $this->generateP4Command('depots', false); $this->executeCommand($command); $result = $this->commandResult; $resArray = explode(PHP_EOL, $result); foreach ($resArray as $line) { if (strpos($line, 'Depot') !== false) { $fields = explode(' ', $line); if (strcmp($this->p4Depot, $fields[1]) === 0) { $this->p4DepotType = $fields[3]; return $this->isStream(); } } } return false; } /** * @return mixed|null */ protected function getChangeList(string $reference): mixed { $index = strpos($reference, '@'); if ($index === false) { return null; } $label = substr($reference, $index); $command = $this->generateP4Command(' changes -m1 ' . ProcessExecutor::escape($label)); $this->executeCommand($command); $changes = $this->commandResult; if (strpos($changes, 'Change') !== 0) { return null; } $fields = explode(' ', $changes); return $fields[1]; } /** * @return mixed|null */ public function getCommitLogs(string $fromReference, string $toReference): mixed { $fromChangeList = $this->getChangeList($fromReference); if ($fromChangeList === null) { return null; } $toChangeList = $this->getChangeList($toReference); if ($toChangeList === null) { return null; } $index = strpos($fromReference, '@'); $main = substr($fromReference, 0, $index) . '/...'; $command = $this->generateP4Command('filelog ' . ProcessExecutor::escape($main . '@' . $fromChangeList. ',' . $toChangeList)); $this->executeCommand($command); return $this->commandResult; } public function getFilesystem(): Filesystem { if (null === $this->filesystem) { $this->filesystem = new Filesystem($this->process); } return $this->filesystem; } public function setFilesystem(Filesystem $fs): void { $this->filesystem = $fs; } private function getP4Executable(): string { static $p4Executable; if ($p4Executable) { return $p4Executable; } $finder = new ExecutableFinder(); return $p4Executable = $finder->find('p4') ?? 'p4'; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/HttpDownloader.php
src/Composer/Util/HttpDownloader.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\Util; use Composer\Config; use Composer\IO\IOInterface; use Composer\Downloader\TransportException; use Composer\Pcre\Preg; use Composer\Util\Http\Response; use Composer\Util\Http\CurlDownloader; use Composer\Composer; use Composer\Package\Version\VersionParser; use Composer\Semver\Constraint\Constraint; use Composer\Exception\IrrecoverableDownloadException; use React\Promise\Promise; use React\Promise\PromiseInterface; /** * @author Jordi Boggiano <j.boggiano@seld.be> * @phpstan-type Request array{url: non-empty-string, options: mixed[], copyTo: string|null} * @phpstan-type Job array{id: int, status: int, request: Request, sync: bool, origin: string, resolve?: callable, reject?: callable, curl_id?: int, response?: Response, exception?: \Throwable} */ class HttpDownloader { private const STATUS_QUEUED = 1; private const STATUS_STARTED = 2; private const STATUS_COMPLETED = 3; private const STATUS_FAILED = 4; private const STATUS_ABORTED = 5; /** @var IOInterface */ private $io; /** @var Config */ private $config; /** @var array<Job> */ private $jobs = []; /** @var mixed[] */ private $options = []; /** @var int */ private $runningJobs = 0; /** @var int */ private $maxJobs = 12; /** @var ?CurlDownloader */ private $curl; /** @var ?RemoteFilesystem */ private $rfs; /** @var int */ private $idGen = 0; /** @var bool */ private $disabled; /** @var bool */ private $allowAsync = false; /** * @param IOInterface $io The IO instance * @param Config $config The config * @param mixed[] $options The options */ public function __construct(IOInterface $io, Config $config, array $options = [], bool $disableTls = false) { $this->io = $io; $this->disabled = (bool) Platform::getEnv('COMPOSER_DISABLE_NETWORK'); // Setup TLS options // The cafile option can be set via config.json if ($disableTls === false) { $this->options = StreamContextFactory::getTlsDefaults($options, $io); } // handle the other externally set options normally. $this->options = array_replace_recursive($this->options, $options); $this->config = $config; if (self::isCurlEnabled()) { $this->curl = new CurlDownloader($io, $config, $options, $disableTls); } $this->rfs = new RemoteFilesystem($io, $config, $options, $disableTls); if (is_numeric($maxJobs = Platform::getEnv('COMPOSER_MAX_PARALLEL_HTTP'))) { $this->maxJobs = max(1, min(50, (int) $maxJobs)); } } /** * Download a file synchronously * * @param string $url URL to download * @param mixed[] $options Stream context options e.g. https://www.php.net/manual/en/context.http.php * although not all options are supported when using the default curl downloader * @throws TransportException * @return Response */ public function get(string $url, array $options = []) { if ('' === $url) { throw new \InvalidArgumentException('$url must not be an empty string'); } [$job, $promise] = $this->addJob(['url' => $url, 'options' => $options, 'copyTo' => null], true); $promise->then(null, static function (\Throwable $e) { // suppress error as it is rethrown to the caller by getResponse() a few lines below }); $this->wait($job['id']); $response = $this->getResponse($job['id']); return $response; } /** * Create an async download operation * * @param string $url URL to download * @param mixed[] $options Stream context options e.g. https://www.php.net/manual/en/context.http.php * although not all options are supported when using the default curl downloader * @throws TransportException * @return PromiseInterface * @phpstan-return PromiseInterface<Response> */ public function add(string $url, array $options = []) { if ('' === $url) { throw new \InvalidArgumentException('$url must not be an empty string'); } [, $promise] = $this->addJob(['url' => $url, 'options' => $options, 'copyTo' => null]); return $promise; } /** * Copy a file synchronously * * @param string $url URL to download * @param string $to Path to copy to * @param mixed[] $options Stream context options e.g. https://www.php.net/manual/en/context.http.php * although not all options are supported when using the default curl downloader * @throws TransportException * @return Response */ public function copy(string $url, string $to, array $options = []) { if ('' === $url) { throw new \InvalidArgumentException('$url must not be an empty string'); } [$job] = $this->addJob(['url' => $url, 'options' => $options, 'copyTo' => $to], true); $this->wait($job['id']); return $this->getResponse($job['id']); } /** * Create an async copy operation * * @param string $url URL to download * @param string $to Path to copy to * @param mixed[] $options Stream context options e.g. https://www.php.net/manual/en/context.http.php * although not all options are supported when using the default curl downloader * @throws TransportException * @return PromiseInterface * @phpstan-return PromiseInterface<Response> */ public function addCopy(string $url, string $to, array $options = []) { if ('' === $url) { throw new \InvalidArgumentException('$url must not be an empty string'); } [, $promise] = $this->addJob(['url' => $url, 'options' => $options, 'copyTo' => $to]); return $promise; } /** * Retrieve the options set in the constructor * * @return mixed[] Options */ public function getOptions() { return $this->options; } /** * Merges new options * * @param mixed[] $options * @return void */ public function setOptions(array $options) { $this->options = array_replace_recursive($this->options, $options); } /** * @phpstan-param Request $request * @return array{Job, PromiseInterface} * @phpstan-return array{Job, PromiseInterface<Response>} */ private function addJob(array $request, bool $sync = false): array { $request['options'] = array_replace_recursive($this->options, $request['options']); /** @var Job */ $job = [ 'id' => $this->idGen++, 'status' => self::STATUS_QUEUED, 'request' => $request, 'sync' => $sync, 'origin' => Url::getOrigin($this->config, $request['url']), ]; if (!$sync && !$this->allowAsync) { throw new \LogicException('You must use the HttpDownloader instance which is part of a Composer\Loop instance to be able to run async http requests'); } // capture username/password from URL if there is one if (Preg::isMatchStrictGroups('{^https?://([^:/]+):([^@/]+)@([^/]+)}i', $request['url'], $match)) { $this->io->setAuthentication($job['origin'], rawurldecode($match[1]), rawurldecode($match[2])); } $rfs = $this->rfs; if ($this->canUseCurl($job)) { $resolver = static function ($resolve, $reject) use (&$job): void { $job['status'] = HttpDownloader::STATUS_QUEUED; $job['resolve'] = $resolve; $job['reject'] = $reject; }; } else { $resolver = static function ($resolve, $reject) use (&$job, $rfs): void { // start job $url = $job['request']['url']; $options = $job['request']['options']; $job['status'] = HttpDownloader::STATUS_STARTED; if ($job['request']['copyTo']) { $rfs->copy($job['origin'], $url, $job['request']['copyTo'], false /* TODO progress */, $options); $headers = $rfs->getLastHeaders(); $response = new Response($job['request'], $rfs->findStatusCode($headers), $headers, $job['request']['copyTo'].'~'); $resolve($response); } else { $body = $rfs->getContents($job['origin'], $url, false /* TODO progress */, $options); $headers = $rfs->getLastHeaders(); $response = new Response($job['request'], $rfs->findStatusCode($headers), $headers, $body); $resolve($response); } }; } $curl = $this->curl; $canceler = static function () use (&$job, $curl): void { if ($job['status'] === HttpDownloader::STATUS_QUEUED) { $job['status'] = HttpDownloader::STATUS_ABORTED; } if ($job['status'] !== HttpDownloader::STATUS_STARTED) { return; } $job['status'] = HttpDownloader::STATUS_ABORTED; if (isset($job['curl_id'])) { $curl->abortRequest($job['curl_id']); } throw new IrrecoverableDownloadException('Download of ' . Url::sanitize($job['request']['url']) . ' canceled'); }; $promise = new Promise($resolver, $canceler); $promise = $promise->then(function ($response) use (&$job) { $job['status'] = HttpDownloader::STATUS_COMPLETED; $job['response'] = $response; $this->markJobDone(); return $response; }, function ($e) use (&$job): void { $job['status'] = HttpDownloader::STATUS_FAILED; $job['exception'] = $e; $this->markJobDone(); throw $e; }); $this->jobs[$job['id']] = &$job; if ($this->runningJobs < $this->maxJobs) { $this->startJob($job['id']); } return [$job, $promise]; } private function startJob(int $id): void { $job = &$this->jobs[$id]; if ($job['status'] !== self::STATUS_QUEUED) { return; } // start job $job['status'] = self::STATUS_STARTED; $this->runningJobs++; assert(isset($job['resolve'])); assert(isset($job['reject'])); $resolve = $job['resolve']; $reject = $job['reject']; $url = $job['request']['url']; $options = $job['request']['options']; $origin = $job['origin']; if ($this->disabled) { if (isset($job['request']['options']['http']['header']) && false !== stripos(implode('', $job['request']['options']['http']['header']), 'if-modified-since')) { $resolve(new Response(['url' => $url], 304, [], '')); } else { $e = new TransportException('Network disabled, request canceled: '.Url::sanitize($url), 499); $e->setStatusCode(499); $reject($e); } return; } try { if ($job['request']['copyTo']) { $job['curl_id'] = $this->curl->download($resolve, $reject, $origin, $url, $options, $job['request']['copyTo']); } else { $job['curl_id'] = $this->curl->download($resolve, $reject, $origin, $url, $options); } } catch (\Exception $exception) { $reject($exception); } } private function markJobDone(): void { $this->runningJobs--; } /** * Wait for current async download jobs to complete * * @param int|null $index For internal use only, the job id * * @return void */ public function wait(?int $index = null) { do { $jobCount = $this->countActiveJobs($index); } while ($jobCount); } /** * @internal */ public function enableAsync(): void { $this->allowAsync = true; } /** * @internal * * @param int|null $index For internal use only, the job id * @return int number of active (queued or started) jobs */ public function countActiveJobs(?int $index = null): int { if ($this->runningJobs < $this->maxJobs) { foreach ($this->jobs as $job) { if ($job['status'] === self::STATUS_QUEUED && $this->runningJobs < $this->maxJobs) { $this->startJob($job['id']); } } } if ($this->curl) { $this->curl->tick(); } if (null !== $index) { return $this->jobs[$index]['status'] < self::STATUS_COMPLETED ? 1 : 0; } $active = 0; foreach ($this->jobs as $job) { if ($job['status'] < self::STATUS_COMPLETED) { $active++; } elseif (!$job['sync']) { unset($this->jobs[$job['id']]); } } return $active; } /** * @param int $index Job id */ private function getResponse(int $index): Response { if (!isset($this->jobs[$index])) { throw new \LogicException('Invalid request id'); } if ($this->jobs[$index]['status'] === self::STATUS_FAILED) { assert(isset($this->jobs[$index]['exception'])); throw $this->jobs[$index]['exception']; } if (!isset($this->jobs[$index]['response'])) { throw new \LogicException('Response not available yet, call wait() first'); } $resp = $this->jobs[$index]['response']; unset($this->jobs[$index]); return $resp; } /** * @internal * * @param array{warning?: string, info?: string, warning-versions?: string, info-versions?: string, warnings?: array<array{versions: string, message: string}>, infos?: array<array{versions: string, message: string}>} $data */ public static function outputWarnings(IOInterface $io, string $url, $data): void { $cleanMessage = static function ($msg) use ($io) { if (!$io->isDecorated()) { $msg = Preg::replace('{'.chr(27).'\\[[;\d]*m}u', '', $msg); } return $msg; }; // legacy warning/info keys foreach (['warning', 'info'] as $type) { if (empty($data[$type])) { continue; } if (!empty($data[$type . '-versions'])) { $versionParser = new VersionParser(); $constraint = $versionParser->parseConstraints($data[$type . '-versions']); $composer = new Constraint('==', $versionParser->normalize(Composer::getVersion())); if (!$constraint->matches($composer)) { continue; } } $io->writeError('<'.$type.'>'.ucfirst($type).' from '.Url::sanitize($url).': '.$cleanMessage($data[$type]).'</'.$type.'>'); } // modern Composer 2.2+ format with support for multiple warning/info messages foreach (['warnings', 'infos'] as $key) { if (empty($data[$key])) { continue; } $versionParser = new VersionParser(); foreach ($data[$key] as $spec) { $type = substr($key, 0, -1); $constraint = $versionParser->parseConstraints($spec['versions']); $composer = new Constraint('==', $versionParser->normalize(Composer::getVersion())); if (!$constraint->matches($composer)) { continue; } $io->writeError('<'.$type.'>'.ucfirst($type).' from '.Url::sanitize($url).': '.$cleanMessage($spec['message']).'</'.$type.'>'); } } } /** * @internal * * @return ?string[] */ public static function getExceptionHints(\Throwable $e): ?array { if (!$e instanceof TransportException) { return null; } if ( false !== strpos($e->getMessage(), 'Resolving timed out') || false !== strpos($e->getMessage(), 'Could not resolve host') ) { Silencer::suppress(); $testConnectivity = file_get_contents('https://8.8.8.8', false, stream_context_create([ 'ssl' => ['verify_peer' => false], 'http' => ['follow_location' => false, 'ignore_errors' => true], ])); Silencer::restore(); if (false !== $testConnectivity) { return [ '<error>The following exception probably indicates you have misconfigured DNS resolver(s)</error>', ]; } return [ '<error>The following exception probably indicates you are offline or have misconfigured DNS resolver(s)</error>', ]; } return null; } /** * @param Job $job */ private function canUseCurl(array $job): bool { if (!$this->curl) { return false; } if (!Preg::isMatch('{^https?://}i', $job['request']['url'])) { return false; } if (!empty($job['request']['options']['ssl']['allow_self_signed'])) { return false; } return true; } /** * @internal */ public static function isCurlEnabled(): bool { return \extension_loaded('curl') && \function_exists('curl_multi_exec') && \function_exists('curl_multi_init'); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Git.php
src/Composer/Util/Git.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\Util; use Composer\Config; use Composer\IO\IOInterface; use Composer\Pcre\Preg; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class Git { /** @var string|false|null */ private static $version = false; /** @var IOInterface */ protected $io; /** @var Config */ protected $config; /** @var ProcessExecutor */ protected $process; /** @var Filesystem */ protected $filesystem; /** @var HttpDownloader */ protected $httpDownloader; public function __construct(IOInterface $io, Config $config, ProcessExecutor $process, Filesystem $fs) { $this->io = $io; $this->config = $config; $this->process = $process; $this->filesystem = $fs; } /** * @param IOInterface|null $io If present, a warning is output there instead of throwing, so pass this in only for cases where this is a soft failure */ public static function checkForRepoOwnershipError(string $output, string $path, ?IOInterface $io = null): void { if (str_contains($output, 'fatal: detected dubious ownership')) { $msg = 'The repository at "' . $path . '" does not have the correct ownership and git refuses to use it:' . PHP_EOL . PHP_EOL . $output; if ($io === null) { throw new \RuntimeException($msg); } $io->writeError('<warning>'.$msg.'</warning>'); } } public function setHttpDownloader(HttpDownloader $httpDownloader): void { $this->httpDownloader = $httpDownloader; } /** * Runs a set of commands using the $url or a variation of it (with auth, ssh, ..) * * Commands should use %url% placeholders for the URL instead of inlining it to allow this function to do its job * %sanitizedUrl% is also automatically replaced by the url without user/pass * * As soon as a single command fails it will halt, so assume the commands are run as && in bash * * @param non-empty-array<non-empty-list<string>> $commands * @param mixed $commandOutput the output will be written into this var if passed by ref * if a callable is passed it will be used as output handler */ public function runCommands(array $commands, string $url, ?string $cwd, bool $initialClone = false, &$commandOutput = null): void { $callables = []; foreach ($commands as $cmd) { $callables[] = static function (string $url) use ($cmd): array { $map = [ '%url%' => $url, '%sanitizedUrl%' => Preg::replace('{://([^@]+?):(.+?)@}', '://', $url), ]; return array_map(static function ($value) use ($map): string { return $map[$value] ?? $value; }, $cmd); }; } // @phpstan-ignore method.deprecated $this->runCommand($callables, $url, $cwd, $initialClone, $commandOutput); } /** * @param callable|array<callable> $commandCallable * @param mixed $commandOutput the output will be written into this var if passed by ref * if a callable is passed it will be used as output handler * @deprecated Use runCommands with placeholders instead of callbacks for simplicity */ public function runCommand($commandCallable, string $url, ?string $cwd, bool $initialClone = false, &$commandOutput = null): void { $commandCallables = is_callable($commandCallable) ? [$commandCallable] : $commandCallable; $lastCommand = ''; // Ensure we are allowed to use this URL by config $this->config->prohibitUrlByConfig($url, $this->io); if ($initialClone) { $origCwd = $cwd; } $runCommands = function ($url) use ($commandCallables, $cwd, &$commandOutput, &$lastCommand, $initialClone) { $collectOutputs = !is_callable($commandOutput); $outputs = []; $status = 0; $counter = 0; foreach ($commandCallables as $callable) { $lastCommand = $callable($url); if ($collectOutputs) { $outputs[] = ''; $output = &$outputs[count($outputs) - 1]; } else { $output = &$commandOutput; } $status = $this->process->execute($lastCommand, $output, $initialClone && $counter === 0 ? null : $cwd); if ($status !== 0) { break; } $counter++; } if ($collectOutputs) { $commandOutput = implode('', $outputs); } return $status; }; if (Preg::isMatch('{^ssh://[^@]+@[^:]+:[^0-9]+}', $url)) { throw new \InvalidArgumentException('The source URL ' . $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.'); } if (!$initialClone) { // capture username/password from URL if there is one and we have no auth configured yet $this->process->execute(['git', 'remote', '-v'], $output, $cwd); if (Preg::isMatchStrictGroups('{^(?:composer|origin)\s+https?://(.+):(.+)@([^/]+)}im', $output, $match) && !$this->io->hasAuthentication($match[3])) { $this->io->setAuthentication($match[3], rawurldecode($match[1]), rawurldecode($match[2])); } } $protocols = $this->config->get('github-protocols'); // public github, autoswitch protocols // @phpstan-ignore composerPcre.maybeUnsafeStrictGroups if (Preg::isMatchStrictGroups('{^(?:https?|git)://' . self::getGitHubDomainsRegex($this->config) . '/(.*)}', $url, $match)) { $messages = []; foreach ($protocols as $protocol) { if ('ssh' === $protocol) { $protoUrl = "git@" . $match[1] . ":" . $match[2]; } else { $protoUrl = $protocol . "://" . $match[1] . "/" . $match[2]; } if (0 === $runCommands($protoUrl)) { return; } $messages[] = '- ' . $protoUrl . "\n" . Preg::replace('#^#m', ' ', $this->process->getErrorOutput()); if ($initialClone && isset($origCwd)) { $this->filesystem->removeDirectory($origCwd); } } // failed to checkout, first check git accessibility if (!$this->io->hasAuthentication($match[1]) && !$this->io->isInteractive()) { $this->throwException('Failed to clone ' . $url . ' via ' . implode(', ', $protocols) . ' protocols, aborting.' . "\n\n" . implode("\n", $messages), $url); } } // if we have a private github url and the ssh protocol is disabled then we skip it and directly fallback to https $bypassSshForGitHub = Preg::isMatch('{^git@' . self::getGitHubDomainsRegex($this->config) . ':(.+?)\.git$}i', $url) && !in_array('ssh', $protocols, true); $auth = null; $credentials = []; if ($bypassSshForGitHub || 0 !== $runCommands($url)) { $errorMsg = $this->process->getErrorOutput(); // private github repository without ssh key access, try https with auth // @phpstan-ignore composerPcre.maybeUnsafeStrictGroups if (Preg::isMatchStrictGroups('{^git@' . self::getGitHubDomainsRegex($this->config) . ':(.+?)\.git$}i', $url, $match) // @phpstan-ignore composerPcre.maybeUnsafeStrictGroups || Preg::isMatchStrictGroups('{^https?://' . self::getGitHubDomainsRegex($this->config) . '/(.*?)(?:\.git)?$}i', $url, $match) ) { if (!$this->io->hasAuthentication($match[1])) { $gitHubUtil = new GitHub($this->io, $this->config, $this->process); $message = 'Cloning failed using an ssh key for authentication, enter your GitHub credentials to access private repos'; if (!$gitHubUtil->authorizeOAuth($match[1]) && $this->io->isInteractive()) { $gitHubUtil->authorizeOAuthInteractively($match[1], $message); } } if ($this->io->hasAuthentication($match[1])) { $auth = $this->io->getAuthentication($match[1]); $authUrl = 'https://' . rawurlencode($auth['username']) . ':' . rawurlencode($auth['password']) . '@' . $match[1] . '/' . $match[2] . '.git'; if (0 === $runCommands($authUrl)) { return; } $credentials = [rawurlencode($auth['username']), rawurlencode($auth['password'])]; $errorMsg = $this->process->getErrorOutput(); } // @phpstan-ignore composerPcre.maybeUnsafeStrictGroups } elseif ( Preg::isMatchStrictGroups('{^(https?)://(bitbucket\.org)/(.*?)(?:\.git)?$}i', $url, $match) || Preg::isMatchStrictGroups('{^(git)@(bitbucket\.org):(.+?\.git)$}i', $url, $match) ) { //bitbucket either through oauth or app password, with fallback to ssh. $bitbucketUtil = new Bitbucket($this->io, $this->config, $this->process, $this->httpDownloader); $domain = $match[2]; $repo_with_git_part = $match[3]; if (!str_ends_with($repo_with_git_part, '.git')) { $repo_with_git_part .= '.git'; } if (!$this->io->hasAuthentication($domain)) { $message = 'Enter your Bitbucket credentials to access private repos'; if (!$bitbucketUtil->authorizeOAuth($domain) && $this->io->isInteractive()) { $bitbucketUtil->authorizeOAuthInteractively($domain, $message); $accessToken = $bitbucketUtil->getToken(); $this->io->setAuthentication($domain, 'x-token-auth', $accessToken); } } // First we try to authenticate with whatever we have stored. // This will be successful if there is for example an app // password in there. if ($this->io->hasAuthentication($domain)) { $auth = $this->io->getAuthentication($domain); // Bitbucket API tokens use the email address as the username for HTTP API calls and // either the Bitbucket username or 'x-bitbucket-api-token-auth' as the username for git operations. if (strpos((string) $auth['password'], 'ATAT') === 0) { $auth['username'] = 'x-bitbucket-api-token-auth'; } $authUrl = 'https://' . rawurlencode($auth['username']) . ':' . rawurlencode($auth['password']) . '@' . $domain . '/' . $repo_with_git_part; if (0 === $runCommands($authUrl)) { // Well if that succeeded on our first try, let's just // take the win. return; } //We already have an access_token from a previous request. if ($auth['username'] !== 'x-token-auth') { $accessToken = $bitbucketUtil->requestToken($domain, $auth['username'], $auth['password']); if (!empty($accessToken)) { $this->io->setAuthentication($domain, 'x-token-auth', $accessToken); } } } if ($this->io->hasAuthentication($domain)) { $auth = $this->io->getAuthentication($domain); $authUrl = 'https://' . rawurlencode($auth['username']) . ':' . rawurlencode($auth['password']) . '@' . $domain . '/' . $repo_with_git_part; if (0 === $runCommands($authUrl)) { return; } $credentials = [rawurlencode($auth['username']), rawurlencode($auth['password'])]; } //Falling back to ssh $sshUrl = 'git@bitbucket.org:' . $repo_with_git_part; $this->io->writeError(' No bitbucket authentication configured. Falling back to ssh.'); if (0 === $runCommands($sshUrl)) { return; } $errorMsg = $this->process->getErrorOutput(); } elseif ( // @phpstan-ignore composerPcre.maybeUnsafeStrictGroups Preg::isMatchStrictGroups('{^(git)@' . self::getGitLabDomainsRegex($this->config) . ':(.+?\.git)$}i', $url, $match) // @phpstan-ignore composerPcre.maybeUnsafeStrictGroups || Preg::isMatchStrictGroups('{^(https?)://' . self::getGitLabDomainsRegex($this->config) . '/(.*)}i', $url, $match) ) { if ($match[1] === 'git') { $match[1] = 'https'; } if (!$this->io->hasAuthentication($match[2])) { $gitLabUtil = new GitLab($this->io, $this->config, $this->process); $message = 'Cloning failed, enter your GitLab credentials to access private repos'; if (!$gitLabUtil->authorizeOAuth($match[2]) && $this->io->isInteractive()) { $gitLabUtil->authorizeOAuthInteractively($match[1], $match[2], $message); } } if ($this->io->hasAuthentication($match[2])) { $auth = $this->io->getAuthentication($match[2]); if ($auth['password'] === 'private-token' || $auth['password'] === 'oauth2' || $auth['password'] === 'gitlab-ci-token') { $authUrl = $match[1] . '://' . rawurlencode($auth['password']) . ':' . rawurlencode((string) $auth['username']) . '@' . $match[2] . '/' . $match[3]; // swap username and password } else { $authUrl = $match[1] . '://' . rawurlencode((string) $auth['username']) . ':' . rawurlencode((string) $auth['password']) . '@' . $match[2] . '/' . $match[3]; } if (0 === $runCommands($authUrl)) { return; } $credentials = [rawurlencode((string) $auth['username']), rawurlencode((string) $auth['password'])]; $errorMsg = $this->process->getErrorOutput(); } } elseif (null !== ($match = $this->getAuthenticationFailure($url))) { // private non-github/gitlab/bitbucket repo that failed to authenticate if (str_contains($match[2], '@')) { [$authParts, $match[2]] = explode('@', $match[2], 2); } $storeAuth = false; if ($this->io->hasAuthentication($match[2])) { $auth = $this->io->getAuthentication($match[2]); } elseif ($this->io->isInteractive()) { $defaultUsername = null; if (isset($authParts) && $authParts !== '') { if (str_contains($authParts, ':')) { [$defaultUsername] = explode(':', $authParts, 2); } else { $defaultUsername = $authParts; } } $this->io->writeError(' Authentication required (<info>' . $match[2] . '</info>):'); $this->io->writeError('<warning>' . trim($errorMsg) . '</warning>', true, IOInterface::VERBOSE); $auth = [ 'username' => $this->io->ask(' Username: ', $defaultUsername), 'password' => $this->io->askAndHideAnswer(' Password: '), ]; $storeAuth = $this->config->get('store-auths'); } if (null !== $auth) { $authUrl = $match[1] . rawurlencode((string) $auth['username']) . ':' . rawurlencode((string) $auth['password']) . '@' . $match[2] . $match[3]; if (0 === $runCommands($authUrl)) { $this->io->setAuthentication($match[2], $auth['username'], $auth['password']); $authHelper = new AuthHelper($this->io, $this->config); $authHelper->storeAuth($match[2], $storeAuth); return; } $credentials = [rawurlencode((string) $auth['username']), rawurlencode((string) $auth['password'])]; $errorMsg = $this->process->getErrorOutput(); } } if ($initialClone && isset($origCwd)) { $this->filesystem->removeDirectory($origCwd); } if (\is_array($lastCommand)) { $lastCommand = implode(' ', $lastCommand); } if (count($credentials) > 0) { $lastCommand = $this->maskCredentials($lastCommand, $credentials); $errorMsg = $this->maskCredentials($errorMsg, $credentials); } $this->throwException('Failed to execute ' . $lastCommand . "\n\n" . $errorMsg, $url); } } public function syncMirror(string $url, string $dir): bool { if ((bool) Platform::getEnv('COMPOSER_DISABLE_NETWORK') && Platform::getEnv('COMPOSER_DISABLE_NETWORK') !== 'prime') { $this->io->writeError('<warning>Aborting git mirror sync of '.$url.' as network is disabled</warning>'); return false; } // update the repo if it is a valid git repository if (is_dir($dir) && 0 === $this->process->execute(['git', 'rev-parse', '--git-dir'], $output, $dir) && trim($output) === '.') { try { $commands = [ ['git', 'remote', 'set-url', 'origin', '--', '%url%'], ['git', 'remote', 'update', '--prune', 'origin'], ['git', 'remote', 'set-url', 'origin', '--', '%sanitizedUrl%'], ['git', 'gc', '--auto'], ]; $this->runCommands($commands, $url, $dir); } catch (\Exception $e) { $this->io->writeError('<error>Sync mirror failed: ' . $e->getMessage() . '</error>', true, IOInterface::DEBUG); return false; } return true; } self::checkForRepoOwnershipError($this->process->getErrorOutput(), $dir); // clean up directory and do a fresh clone into it $this->filesystem->removeDirectory($dir); $this->runCommands([['git', 'clone', '--mirror', '--', '%url%', $dir]], $url, $dir, true); return true; } public function fetchRefOrSyncMirror(string $url, string $dir, string $ref, ?string $prettyVersion = null): bool { if ($this->checkRefIsInMirror($dir, $ref)) { if (Preg::isMatch('{^[a-f0-9]{40}$}', $ref) && $prettyVersion !== null) { $branch = Preg::replace('{(?:^dev-|(?:\.x)?-dev$)}i', '', $prettyVersion); $branches = null; $tags = null; if (0 === $this->process->execute(['git', 'branch'], $output, $dir)) { $branches = $output; } if (0 === $this->process->execute(['git', 'tag'], $output, $dir)) { $tags = $output; } // if the pretty version cannot be found as a branch (nor branch with 'v' in front of the branch as it may have been stripped when generating pretty name), // nor as a tag, then we sync the mirror as otherwise it will likely fail during install. // this can occur if a git tag gets created *after* the reference is already put into the cache, as the ref check above will then not sync the new tags // see https://github.com/composer/composer/discussions/11002 if (null !== $branches && !Preg::isMatch('{^[\s*]*v?'.preg_quote($branch).'$}m', $branches) && null !== $tags && !Preg::isMatch('{^[\s*]*'.preg_quote($branch).'$}m', $tags) ) { $this->syncMirror($url, $dir); } } return true; } if ($this->syncMirror($url, $dir)) { return $this->checkRefIsInMirror($dir, $ref); } return false; } public static function getNoShowSignatureFlag(ProcessExecutor $process): string { $gitVersion = self::getVersion($process); if ($gitVersion !== null && version_compare($gitVersion, '2.10.0-rc0', '>=')) { return ' --no-show-signature'; } return ''; } /** * @return list<string> */ public static function getNoShowSignatureFlags(ProcessExecutor $process): array { $flags = static::getNoShowSignatureFlag($process); if ('' === $flags) { return []; } return explode(' ', substr($flags, 1)); } /** * Checks if git version supports --no-commit-header flag (git 2.33+) * * @internal */ public static function supportsNoCommitHeaderFlag(ProcessExecutor $process): bool { $gitVersion = self::getVersion($process); return $gitVersion !== null && version_compare($gitVersion, '2.33.0-rc0', '>='); } /** * Builds a git rev-list command with --no-commit-header flag when supported (git 2.33+) * * @internal * @param list<string> $arguments Additional arguments for git rev-list * @return non-empty-list<string> */ public static function buildRevListCommand(ProcessExecutor $process, array $arguments): array { $command = ['git', 'rev-list']; if (self::supportsNoCommitHeaderFlag($process)) { $command[] = '--no-commit-header'; } return array_merge($command, $arguments); } /** * Parses git rev-list output, removing 'commit <hash>' header lines for git < 2.33. * * When --no-commit-header is not available (git < 2.33), git rev-list --format outputs * "commit <hash>" before formatted output. This removes those lines. * * @internal */ public static function parseRevListOutput(string $output, ProcessExecutor $process): string { // If git supports --no-commit-header, output is already clean if (self::supportsNoCommitHeaderFlag($process)) { return $output; } // Filter out "commit <hash>" lines for older git versions return Preg::replace('{^commit [a-f0-9]{40}\n?}m', '', $output); } private function checkRefIsInMirror(string $dir, string $ref): bool { if (is_dir($dir) && 0 === $this->process->execute(['git', 'rev-parse', '--git-dir'], $output, $dir) && trim($output) === '.') { $exitCode = $this->process->execute(['git', 'rev-parse', '--quiet', '--verify', $ref.'^{commit}'], $ignoredOutput, $dir); if ($exitCode === 0) { return true; } } self::checkForRepoOwnershipError($this->process->getErrorOutput(), $dir); return false; } /** * @return array<int, string>|null */ private function getAuthenticationFailure(string $url): ?array { if (!Preg::isMatchStrictGroups('{^(https?://)([^/]+)(.*)$}i', $url, $match)) { return null; } $authFailures = [ 'fatal: Authentication failed', 'remote error: Invalid username or password.', 'error: 401 Unauthorized', 'fatal: unable to access', 'fatal: could not read Username', ]; $errorOutput = $this->process->getErrorOutput(); foreach ($authFailures as $authFailure) { if (strpos($errorOutput, $authFailure) !== false) { return $match; } } return null; } public function getMirrorDefaultBranch(string $url, string $dir, bool $isLocalPathRepository): ?string { if ((bool) Platform::getEnv('COMPOSER_DISABLE_NETWORK')) { return null; } try { if ($isLocalPathRepository) { $this->process->execute(['git', 'remote', 'show', 'origin'], $output, $dir); } else { $commands = [ ['git', 'remote', 'set-url', 'origin', '--', '%url%'], ['git', 'remote', 'show', 'origin'], ['git', 'remote', 'set-url', 'origin', '--', '%sanitizedUrl%'], ]; $this->runCommands($commands, $url, $dir, false, $output); } $lines = $this->process->splitLines($output); foreach ($lines as $line) { if (Preg::isMatch('{^\s*HEAD branch:\s(.+)\s*$}m', $line, $matches)) { return $matches[1]; } } } catch (\Exception $e) { $this->io->writeError('<error>Failed to fetch root identifier from remote: ' . $e->getMessage() . '</error>', true, IOInterface::DEBUG); } return null; } public static function cleanEnv(?ProcessExecutor $process = null): void { $gitVersion = self::getVersion($process ?? new ProcessExecutor()); if ($gitVersion !== null && version_compare($gitVersion, '2.3.0', '>=')) { // added in git 2.3.0, prevents prompting the user for username/password if (Platform::getEnv('GIT_TERMINAL_PROMPT') !== '0') { Platform::putEnv('GIT_TERMINAL_PROMPT', '0'); } } else { // added in git 1.7.1, prevents prompting the user for username/password if (Platform::getEnv('GIT_ASKPASS') !== 'echo') { Platform::putEnv('GIT_ASKPASS', 'echo'); } } // clean up rogue git env vars in case this is running in a git hook if (Platform::getEnv('GIT_DIR')) { Platform::clearEnv('GIT_DIR'); } if (Platform::getEnv('GIT_WORK_TREE')) { Platform::clearEnv('GIT_WORK_TREE'); } // Run processes with predictable LANGUAGE if (Platform::getEnv('LANGUAGE') !== 'C') { Platform::putEnv('LANGUAGE', 'C'); } // clean up env for OSX, see https://github.com/composer/composer/issues/2146#issuecomment-35478940 Platform::clearEnv('DYLD_LIBRARY_PATH'); } /** * @return non-empty-string */ public static function getGitHubDomainsRegex(Config $config): string { return '(' . implode('|', array_map('preg_quote', $config->get('github-domains'))) . ')'; } /** * @return non-empty-string */ public static function getGitLabDomainsRegex(Config $config): string { return '(' . implode('|', array_map('preg_quote', $config->get('gitlab-domains'))) . ')'; } /** * @param non-empty-string $message * * @return never */ private function throwException($message, string $url): void { // git might delete a directory when it fails and php will not know clearstatcache(); if (0 !== $this->process->execute(['git', '--version'], $ignoredOutput)) { throw new \RuntimeException(Url::sanitize('Failed to clone ' . $url . ', git was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput())); } throw new \RuntimeException(Url::sanitize($message)); } /** * Retrieves the current git version. * * @return string|null The git version number, if present. */ public static function getVersion(ProcessExecutor $process): ?string { if (false === self::$version) { self::$version = null; if (0 === $process->execute(['git', '--version'], $output) && Preg::isMatch('/^git version (\d+(?:\.\d+)+)/m', $output, $matches)) { self::$version = $matches[1]; } } return self::$version; } /** * @param string[] $credentials */ private function maskCredentials(string $error, array $credentials): string { $maskedCredentials = []; foreach ($credentials as $credential) { if (in_array($credential, ['private-token', 'x-token-auth', 'oauth2', 'gitlab-ci-token', 'x-oauth-basic'])) { $maskedCredentials[] = $credential; } elseif (strlen($credential) > 6) { $maskedCredentials[] = substr($credential, 0, 3) . '...' . substr($credential, -3); } elseif (strlen($credential) > 3) { $maskedCredentials[] = substr($credential, 0, 3) . '...'; } else { $maskedCredentials[] = 'XXX'; } } return str_replace($credentials, $maskedCredentials, $error); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/GitHub.php
src/Composer/Util/GitHub.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\Util; use Composer\Factory; use Composer\IO\IOInterface; use Composer\Config; use Composer\Downloader\TransportException; use Composer\Pcre\Preg; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class GitHub { public const GITHUB_TOKEN_REGEX = '{^([a-f0-9]{12,}|gh[a-z]_[a-zA-Z0-9_]+|github_pat_[a-zA-Z0-9_]+)$}'; /** @var IOInterface */ protected $io; /** @var Config */ protected $config; /** @var ProcessExecutor */ protected $process; /** @var HttpDownloader */ protected $httpDownloader; /** * Constructor. * * @param IOInterface $io The IO instance * @param Config $config The composer configuration * @param ProcessExecutor $process Process instance, injectable for mocking * @param HttpDownloader $httpDownloader Remote Filesystem, injectable for mocking */ public function __construct(IOInterface $io, Config $config, ?ProcessExecutor $process = null, ?HttpDownloader $httpDownloader = null) { $this->io = $io; $this->config = $config; $this->process = $process ?: new ProcessExecutor($io); $this->httpDownloader = $httpDownloader ?: Factory::createHttpDownloader($this->io, $config); } /** * Attempts to authorize a GitHub domain via OAuth * * @param string $originUrl The host this GitHub instance is located at * @return bool true on success */ public function authorizeOAuth(string $originUrl): bool { if (!in_array($originUrl, $this->config->get('github-domains'))) { return false; } // if available use token from git config if (0 === $this->process->execute(['git', 'config', 'github.accesstoken'], $output)) { $this->io->setAuthentication($originUrl, trim($output), 'x-oauth-basic'); return true; } return false; } /** * Authorizes a GitHub domain interactively via OAuth * * @param string $originUrl The host this GitHub instance is located at * @param string $message The reason this authorization is required * @throws \RuntimeException * @throws TransportException|\Exception * @return bool true on success */ public function authorizeOAuthInteractively(string $originUrl, ?string $message = null): bool { if ($message) { $this->io->writeError($message); } $note = 'Composer'; if ($this->config->get('github-expose-hostname') === true && 0 === $this->process->execute(['hostname'], $output)) { $note .= ' on ' . trim($output); } $note .= ' ' . date('Y-m-d Hi'); $localAuthConfig = $this->config->getLocalAuthConfigSource(); $this->io->writeError([ 'You need to provide a GitHub access token.', sprintf('Tokens will be stored in plain text in "%s" for future use by Composer.', ($localAuthConfig !== null ? $localAuthConfig->getName() . ' OR ' : '') . $this->config->getAuthConfigSource()->getName()), 'Due to the security risk of tokens being exfiltrated, use tokens with short expiration times and only the minimum permissions necessary.', '', 'Carefully consider the following options in order:', '', ]); $this->io->writeError([ '1. When you don\'t use \'vcs\' type \'repositories\' in composer.json and do not need to clone source or download dist files', 'from private GitHub repositories over HTTPS, use a fine-grained token with read-only access to public information.', 'Use the following URL to create such a token:', 'https://'.$originUrl.'/settings/personal-access-tokens/new?name=' . str_replace('%20', '+', rawurlencode($note)), '', ]); $this->io->writeError([ '2. When all relevant _private_ GitHub repositories belong to a single user or organisation, use a fine-grained token with', 'repository "content" read-only permissions. You can start with the following URL, but you may need to change the resource owner', 'to the right user or organisation. Additionally, you can scope permissions down to apply only to selected repositories.', 'https://'.$originUrl.'/settings/personal-access-tokens/new?contents=read&name=' . str_replace('%20', '+', rawurlencode($note)), '', ]); $this->io->writeError([ '3. A "classic" token grants broad permissions on your behalf to all repositories accessible by you.', 'This may include write permissions, even though not needed by Composer. Use it only when you need to access', 'private repositories across multiple organisations at the same time and using directory-specific authentication sources', 'is not an option. You can generate a classic token here:', 'https://'.$originUrl.'/settings/tokens/new?scopes=repo&description=' . str_replace('%20', '+', rawurlencode($note)), '', ]); $this->io->writeError('For additional information, check https://getcomposer.org/doc/articles/authentication-for-private-packages.md#github-oauth'); $storeInLocalAuthConfig = false; if ($localAuthConfig !== null) { $storeInLocalAuthConfig = $this->io->askConfirmation('A local auth config source was found, do you want to store the token there?', true); } $token = trim((string) $this->io->askAndHideAnswer('Token (hidden): ')); if ($token === '') { $this->io->writeError('<warning>No token given, aborting.</warning>'); $this->io->writeError('You can also add it manually later by using "composer config --global --auth github-oauth.github.com <token>"'); return false; } $this->io->setAuthentication($originUrl, $token, 'x-oauth-basic'); try { $apiUrl = ('github.com' === $originUrl) ? 'api.github.com/' : $originUrl . '/api/v3/'; $this->httpDownloader->get('https://'. $apiUrl, [ 'retry-auth-failure' => false, ]); } catch (TransportException $e) { if (in_array($e->getCode(), [403, 401])) { $this->io->writeError('<error>Invalid token provided.</error>'); $this->io->writeError('You can also add it manually later by using "composer config --global --auth github-oauth.github.com <token>"'); return false; } throw $e; } // store value in local/user config $authConfigSource = $storeInLocalAuthConfig && $localAuthConfig !== null ? $localAuthConfig : $this->config->getAuthConfigSource(); $this->config->getConfigSource()->removeConfigSetting('github-oauth.'.$originUrl); $authConfigSource->addConfigSetting('github-oauth.'.$originUrl, $token); $this->io->writeError('<info>Token stored successfully.</info>'); return true; } /** * Extract rate limit from response. * * @param string[] $headers Headers from Composer\Downloader\TransportException. * * @return array{limit: int|'?', reset: string} */ public function getRateLimit(array $headers): array { $rateLimit = [ 'limit' => '?', 'reset' => '?', ]; foreach ($headers as $header) { $header = trim($header); if (false === stripos($header, 'x-ratelimit-')) { continue; } [$type, $value] = explode(':', $header, 2); switch (strtolower($type)) { case 'x-ratelimit-limit': $rateLimit['limit'] = (int) trim($value); break; case 'x-ratelimit-reset': $rateLimit['reset'] = date('Y-m-d H:i:s', (int) trim($value)); break; } } return $rateLimit; } /** * Extract SSO URL from response. * * @param string[] $headers Headers from Composer\Downloader\TransportException. */ public function getSsoUrl(array $headers): ?string { foreach ($headers as $header) { $header = trim($header); if (false === stripos($header, 'x-github-sso: required')) { continue; } if (Preg::isMatch('{\burl=(?P<url>[^\s;]+)}', $header, $match)) { return $match['url']; } } return null; } /** * Finds whether a request failed due to rate limiting * * @param string[] $headers Headers from Composer\Downloader\TransportException. */ public function isRateLimited(array $headers): bool { foreach ($headers as $header) { if (Preg::isMatch('{^x-ratelimit-remaining: *0$}i', trim($header))) { return true; } } return false; } /** * Finds whether a request failed due to lacking SSO authorization * * @see https://docs.github.com/en/rest/overview/other-authentication-methods#authenticating-for-saml-sso * * @param string[] $headers Headers from Composer\Downloader\TransportException. */ public function requiresSso(array $headers): bool { foreach ($headers as $header) { if (Preg::isMatch('{^x-github-sso: required}i', trim($header))) { 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/Util/SyncHelper.php
src/Composer/Util/SyncHelper.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\Util; use Composer\Downloader\DownloaderInterface; use Composer\Downloader\DownloadManager; use Composer\Package\PackageInterface; use React\Promise\PromiseInterface; class SyncHelper { /** * Helps you download + install a single package in a synchronous way * * This executes all the required steps and waits for promises to complete * * @param Loop $loop Loop instance which you can get from $composer->getLoop() * @param DownloaderInterface|DownloadManager $downloader DownloadManager instance or Downloader instance you can get from $composer->getDownloadManager()->getDownloader('zip') for example * @param string $path The installation path for the package * @param PackageInterface $package The package to install * @param PackageInterface|null $prevPackage The previous package if this is an update and not an initial installation */ public static function downloadAndInstallPackageSync(Loop $loop, $downloader, string $path, PackageInterface $package, ?PackageInterface $prevPackage = null): void { assert($downloader instanceof DownloaderInterface || $downloader instanceof DownloadManager); $type = $prevPackage !== null ? 'update' : 'install'; try { self::await($loop, $downloader->download($package, $path, $prevPackage)); self::await($loop, $downloader->prepare($type, $package, $path, $prevPackage)); if ($type === 'update' && $prevPackage !== null) { self::await($loop, $downloader->update($package, $prevPackage, $path)); } else { self::await($loop, $downloader->install($package, $path)); } } catch (\Exception $e) { self::await($loop, $downloader->cleanup($type, $package, $path, $prevPackage)); throw $e; } self::await($loop, $downloader->cleanup($type, $package, $path, $prevPackage)); } /** * Waits for a promise to resolve * * @param Loop $loop Loop instance which you can get from $composer->getLoop() * @phpstan-param PromiseInterface<mixed>|null $promise */ public static function await(Loop $loop, ?PromiseInterface $promise = null): void { if ($promise !== null) { $loop->wait([$promise]); } } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Hg.php
src/Composer/Util/Hg.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\Util; use Composer\Config; use Composer\IO\IOInterface; use Composer\Pcre\Preg; /** * @author Jonas Renaudot <jonas.renaudot@gmail.com> */ class Hg { /** @var string|false|null */ private static $version = false; /** * @var IOInterface */ private $io; /** * @var Config */ private $config; /** * @var ProcessExecutor */ private $process; public function __construct(IOInterface $io, Config $config, ProcessExecutor $process) { $this->io = $io; $this->config = $config; $this->process = $process; } public function runCommand(callable $commandCallable, string $url, ?string $cwd): void { $this->config->prohibitUrlByConfig($url, $this->io); // Try as is $command = $commandCallable($url); if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) { return; } // Try with the authentication information available if ( Preg::isMatch('{^(?P<proto>ssh|https?)://(?:(?P<user>[^:@]+)(?::(?P<pass>[^:@]+))?@)?(?P<host>[^/]+)(?P<path>/.*)?}mi', $url, $matches) && $this->io->hasAuthentication($matches['host']) ) { if ($matches['proto'] === 'ssh') { $user = ''; if ($matches['user'] !== null) { $user = rawurlencode($matches['user']) . '@'; } $authenticatedUrl = $matches['proto'] . '://' . $user . $matches['host'] . $matches['path']; } else { $auth = $this->io->getAuthentication($matches['host']); $authenticatedUrl = $matches['proto'] . '://' . rawurlencode((string) $auth['username']) . ':' . rawurlencode((string) $auth['password']) . '@' . $matches['host'] . $matches['path']; } $command = $commandCallable($authenticatedUrl); if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) { return; } $error = $this->process->getErrorOutput(); } else { $error = 'The given URL (' .$url. ') does not match the required format (ssh|http(s)://(username:password@)example.com/path-to-repository)'; } $this->throwException("Failed to clone $url, \n\n" . $error, $url); } /** * @param non-empty-string $message * * @return never */ private function throwException($message, string $url): void { if (null === self::getVersion($this->process)) { throw new \RuntimeException(Url::sanitize( 'Failed to clone ' . $url . ', hg was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput() )); } throw new \RuntimeException(Url::sanitize($message)); } /** * Retrieves the current hg version. * * @return string|null The hg version number, if present. */ public static function getVersion(ProcessExecutor $process): ?string { if (false === self::$version) { self::$version = null; if (0 === $process->execute(['hg', '--version'], $output) && Preg::isMatch('/^.+? (\d+(?:\.\d+)+)(?:\+.*?)?\)?\r?\n/', $output, $matches)) { self::$version = $matches[1]; } } return self::$version; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/NoProxyPattern.php
src/Composer/Util/NoProxyPattern.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\Util; use Composer\Pcre\Preg; use stdClass; /** * Tests URLs against NO_PROXY patterns */ class NoProxyPattern { /** * @var string[] */ protected $hostNames = []; /** * @var (null|object)[] */ protected $rules = []; /** * @var bool */ protected $noproxy; /** * @param string $pattern NO_PROXY pattern */ public function __construct(string $pattern) { $this->hostNames = Preg::split('{[\s,]+}', $pattern, -1, PREG_SPLIT_NO_EMPTY); $this->noproxy = empty($this->hostNames) || '*' === $this->hostNames[0]; } /** * Returns true if a URL matches the NO_PROXY pattern */ public function test(string $url): bool { if ($this->noproxy) { return true; } if (!$urlData = $this->getUrlData($url)) { return false; } foreach ($this->hostNames as $index => $hostName) { if ($this->match($index, $hostName, $urlData)) { return true; } } return false; } /** * Returns false is the url cannot be parsed, otherwise a data object * * @return bool|stdClass */ protected function getUrlData(string $url) { if (!$host = parse_url($url, PHP_URL_HOST)) { return false; } $port = parse_url($url, PHP_URL_PORT); if (empty($port)) { switch (parse_url($url, PHP_URL_SCHEME)) { case 'http': $port = 80; break; case 'https': $port = 443; break; } } $hostName = $host . ($port ? ':' . $port : ''); [$host, $port, $err] = $this->splitHostPort($hostName); if ($err || !$this->ipCheckData($host, $ipdata)) { return false; } return $this->makeData($host, $port, $ipdata); } /** * Returns true if the url is matched by a rule */ protected function match(int $index, string $hostName, stdClass $url): bool { if (!$rule = $this->getRule($index, $hostName)) { // Data must have been misformatted return false; } if ($rule->ipdata) { // Match ipdata first if (!$url->ipdata) { return false; } if ($rule->ipdata->netmask) { return $this->matchRange($rule->ipdata, $url->ipdata); } $match = $rule->ipdata->ip === $url->ipdata->ip; } else { // Match host and port $haystack = substr($url->name, -strlen($rule->name)); $match = stripos($haystack, $rule->name) === 0; } if ($match && $rule->port) { $match = $rule->port === $url->port; } return $match; } /** * Returns true if the target ip is in the network range */ protected function matchRange(stdClass $network, stdClass $target): bool { $net = unpack('C*', $network->ip); $mask = unpack('C*', $network->netmask); $ip = unpack('C*', $target->ip); if (false === $net) { throw new \RuntimeException('Could not parse network IP '.$network->ip); } if (false === $mask) { throw new \RuntimeException('Could not parse netmask '.$network->netmask); } if (false === $ip) { throw new \RuntimeException('Could not parse target IP '.$target->ip); } for ($i = 1; $i < 17; ++$i) { if (($net[$i] & $mask[$i]) !== ($ip[$i] & $mask[$i])) { return false; } } return true; } /** * Finds or creates rule data for a hostname * * @return null|stdClass Null if the hostname is invalid */ private function getRule(int $index, string $hostName): ?stdClass { if (array_key_exists($index, $this->rules)) { return $this->rules[$index]; } $this->rules[$index] = null; [$host, $port, $err] = $this->splitHostPort($hostName); if ($err || !$this->ipCheckData($host, $ipdata, true)) { return null; } $this->rules[$index] = $this->makeData($host, $port, $ipdata); return $this->rules[$index]; } /** * Creates an object containing IP data if the host is an IP address * * @param null|stdClass $ipdata Set by method if IP address found * @param bool $allowPrefix Whether a CIDR prefix-length is expected * * @return bool False if the host contains invalid data */ private function ipCheckData(string $host, ?stdClass &$ipdata, bool $allowPrefix = false): bool { $ipdata = null; $netmask = null; $prefix = null; $modified = false; // Check for a CIDR prefix-length if (strpos($host, '/') !== false) { [$host, $prefix] = explode('/', $host); if (!$allowPrefix || !$this->validateInt($prefix, 0, 128)) { return false; } $prefix = (int) $prefix; $modified = true; } // See if this is an ip address if (!filter_var($host, FILTER_VALIDATE_IP)) { return !$modified; } [$ip, $size] = $this->ipGetAddr($host); if ($prefix !== null) { // Check for a valid prefix if ($prefix > $size * 8) { return false; } [$ip, $netmask] = $this->ipGetNetwork($ip, $size, $prefix); } $ipdata = $this->makeIpData($ip, $size, $netmask); return true; } /** * Returns an array of the IP in_addr and its byte size * * IPv4 addresses are always mapped to IPv6, which simplifies handling * and comparison. * * @return mixed[] in_addr, size */ private function ipGetAddr(string $host): array { $ip = inet_pton($host); $size = strlen($ip); $mapped = $this->ipMapTo6($ip, $size); return [$mapped, $size]; } /** * Returns the binary network mask mapped to IPv6 * * @param int $prefix CIDR prefix-length * @param int $size Byte size of in_addr */ private function ipGetMask(int $prefix, int $size): string { $mask = ''; if ($ones = floor($prefix / 8)) { $mask = str_repeat(chr(255), (int) $ones); } if ($remainder = $prefix % 8) { $mask .= chr(0xff ^ (0xff >> $remainder)); } $mask = str_pad($mask, $size, chr(0)); return $this->ipMapTo6($mask, $size); } /** * Calculates and returns the network and mask * * @param string $rangeIp IP in_addr * @param int $size Byte size of in_addr * @param int $prefix CIDR prefix-length * * @return string[] network in_addr, binary mask */ private function ipGetNetwork(string $rangeIp, int $size, int $prefix): array { $netmask = $this->ipGetMask($prefix, $size); // Get the network from the address and mask $mask = unpack('C*', $netmask); $ip = unpack('C*', $rangeIp); $net = ''; if (false === $mask) { throw new \RuntimeException('Could not parse netmask '.$netmask); } if (false === $ip) { throw new \RuntimeException('Could not parse range IP '.$rangeIp); } for ($i = 1; $i < 17; ++$i) { $net .= chr($ip[$i] & $mask[$i]); } return [$net, $netmask]; } /** * Maps an IPv4 address to IPv6 * * @param string $binary in_addr * @param int $size Byte size of in_addr * * @return string Mapped or existing in_addr */ private function ipMapTo6(string $binary, int $size): string { if ($size === 4) { $prefix = str_repeat(chr(0), 10) . str_repeat(chr(255), 2); $binary = $prefix . $binary; } return $binary; } /** * Creates a rule data object */ private function makeData(string $host, int $port, ?stdClass $ipdata): stdClass { return (object) [ 'host' => $host, 'name' => '.' . ltrim($host, '.'), 'port' => $port, 'ipdata' => $ipdata, ]; } /** * Creates an ip data object * * @param string $ip in_addr * @param int $size Byte size of in_addr * @param null|string $netmask Network mask */ private function makeIpData(string $ip, int $size, ?string $netmask): stdClass { return (object) [ 'ip' => $ip, 'size' => $size, 'netmask' => $netmask, ]; } /** * Splits the hostname into host and port components * * @return mixed[] host, port, if there was error */ private function splitHostPort(string $hostName): array { // host, port, err $error = ['', '', true]; $port = 0; $ip6 = ''; // Check for square-bracket notation if ($hostName[0] === '[') { $index = strpos($hostName, ']'); // The smallest ip6 address is :: if (false === $index || $index < 3) { return $error; } $ip6 = substr($hostName, 1, $index - 1); $hostName = substr($hostName, $index + 1); if (strpbrk($hostName, '[]') !== false || substr_count($hostName, ':') > 1) { return $error; } } if (substr_count($hostName, ':') === 1) { $index = strpos($hostName, ':'); $port = substr($hostName, $index + 1); $hostName = substr($hostName, 0, $index); if (!$this->validateInt($port, 1, 65535)) { return $error; } $port = (int) $port; } $host = $ip6 . $hostName; return [$host, $port, false]; } /** * Wrapper around filter_var FILTER_VALIDATE_INT */ private function validateInt(string $int, int $min, int $max): bool { $options = [ 'options' => [ 'min_range' => $min, 'max_range' => $max, ], ]; return false !== filter_var($int, FILTER_VALIDATE_INT, $options); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/GitLab.php
src/Composer/Util/GitLab.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\Util; use Composer\IO\IOInterface; use Composer\Config; use Composer\Factory; use Composer\Downloader\TransportException; use Composer\Pcre\Preg; /** * @author Roshan Gautam <roshan.gautam@hotmail.com> */ class GitLab { /** @var IOInterface */ protected $io; /** @var Config */ protected $config; /** @var ProcessExecutor */ protected $process; /** @var HttpDownloader */ protected $httpDownloader; /** * Constructor. * * @param IOInterface $io The IO instance * @param Config $config The composer configuration * @param ProcessExecutor $process Process instance, injectable for mocking * @param HttpDownloader $httpDownloader Remote Filesystem, injectable for mocking */ public function __construct(IOInterface $io, Config $config, ?ProcessExecutor $process = null, ?HttpDownloader $httpDownloader = null) { $this->io = $io; $this->config = $config; $this->process = $process ?: new ProcessExecutor($io); $this->httpDownloader = $httpDownloader ?: Factory::createHttpDownloader($this->io, $config); } /** * Attempts to authorize a GitLab domain via OAuth. * * @param string $originUrl The host this GitLab instance is located at * * @return bool true on success */ public function authorizeOAuth(string $originUrl): bool { // before composer 1.9, origin URLs had no port number in them $bcOriginUrl = Preg::replace('{:\d+}', '', $originUrl); if (!in_array($originUrl, $this->config->get('gitlab-domains'), true) && !in_array($bcOriginUrl, $this->config->get('gitlab-domains'), true)) { return false; } // if available use token from git config if (0 === $this->process->execute(['git', 'config', 'gitlab.accesstoken'], $output)) { $this->io->setAuthentication($originUrl, trim($output), 'oauth2'); return true; } // if available use deploy token from git config if (0 === $this->process->execute(['git', 'config', 'gitlab.deploytoken.user'], $tokenUser) && 0 === $this->process->execute(['git', 'config', 'gitlab.deploytoken.token'], $tokenPassword)) { $this->io->setAuthentication($originUrl, trim($tokenUser), trim($tokenPassword)); return true; } // if available use token from composer config $authTokens = $this->config->get('gitlab-token'); if (isset($authTokens[$originUrl])) { $token = $authTokens[$originUrl]; } if (isset($authTokens[$bcOriginUrl])) { $token = $authTokens[$bcOriginUrl]; } if (isset($token)) { $username = is_array($token) ? $token["username"] : $token; $password = is_array($token) ? $token["token"] : 'private-token'; // Composer expects the GitLab token to be stored as username and 'private-token' or 'gitlab-ci-token' to be stored as password // Detect cases where this is reversed and resolve automatically resolve it if (in_array($username, ['private-token', 'gitlab-ci-token', 'oauth2'], true)) { $this->io->setAuthentication($originUrl, $password, $username); } else { $this->io->setAuthentication($originUrl, $username, $password); } return true; } return false; } /** * Authorizes a GitLab domain interactively via OAuth. * * @param string $scheme Scheme used in the origin URL * @param string $originUrl The host this GitLab instance is located at * @param string $message The reason this authorization is required * * @throws \RuntimeException * @throws TransportException|\Exception * * @return bool true on success */ public function authorizeOAuthInteractively(string $scheme, string $originUrl, ?string $message = null): bool { if ($message) { $this->io->writeError($message); } $localAuthConfig = $this->config->getLocalAuthConfigSource(); $personalAccessTokenLink = $scheme.'://'.$originUrl.'/-/user_settings/personal_access_tokens'; $revokeLink = $scheme.'://'.$originUrl.'/-/user_settings/applications'; $this->io->writeError(sprintf('A token will be created and stored in "%s", your password will never be stored', ($localAuthConfig !== null ? $localAuthConfig->getName() . ' OR ' : '') . $this->config->getAuthConfigSource()->getName())); $this->io->writeError('To revoke access to this token you can visit:'); $this->io->writeError($revokeLink); $this->io->writeError('Alternatively you can setup an personal access token on:'); $this->io->writeError($personalAccessTokenLink); $this->io->writeError('and store it under "gitlab-token" see https://getcomposer.org/doc/articles/authentication-for-private-packages.md#gitlab-token for more details.'); $this->io->writeError('https://getcomposer.org/doc/articles/authentication-for-private-packages.md#gitlab-token'); $this->io->writeError('for more details.'); $storeInLocalAuthConfig = false; if ($localAuthConfig !== null) { $storeInLocalAuthConfig = $this->io->askConfirmation('A local auth config source was found, do you want to store the token there?', true); } $attemptCounter = 0; while ($attemptCounter++ < 5) { try { $response = $this->createToken($scheme, $originUrl); } catch (TransportException $e) { // 401 is bad credentials, // 403 is max login attempts exceeded if (in_array($e->getCode(), [403, 401])) { if (401 === $e->getCode()) { $response = json_decode($e->getResponse(), true); if (isset($response['error']) && $response['error'] === 'invalid_grant') { $this->io->writeError('Bad credentials. If you have two factor authentication enabled you will have to manually create a personal access token'); } else { $this->io->writeError('Bad credentials.'); } } else { $this->io->writeError('Maximum number of login attempts exceeded. Please try again later.'); } $this->io->writeError('You can also manually create a personal access token enabling the "read_api" scope at:'); $this->io->writeError($personalAccessTokenLink); $this->io->writeError('Add it using "composer config --global --auth gitlab-token.'.$originUrl.' <token>"'); continue; } throw $e; } $this->io->setAuthentication($originUrl, $response['access_token'], 'oauth2'); $authConfigSource = $storeInLocalAuthConfig && $localAuthConfig !== null ? $localAuthConfig : $this->config->getAuthConfigSource(); // store value in user config in auth file if (isset($response['expires_in'])) { $authConfigSource->addConfigSetting( 'gitlab-oauth.'.$originUrl, [ 'expires-at' => intval($response['created_at']) + intval($response['expires_in']), 'refresh-token' => $response['refresh_token'], 'token' => $response['access_token'], ] ); } else { $authConfigSource->addConfigSetting('gitlab-oauth.'.$originUrl, $response['access_token']); } return true; } throw new \RuntimeException('Invalid GitLab credentials 5 times in a row, aborting.'); } /** * Authorizes a GitLab domain interactively via OAuth. * * @param string $scheme Scheme used in the origin URL * @param string $originUrl The host this GitLab instance is located at * * @throws \RuntimeException * @throws TransportException|\Exception * * @return bool true on success */ public function authorizeOAuthRefresh(string $scheme, string $originUrl): bool { try { $response = $this->refreshToken($scheme, $originUrl); } catch (TransportException $e) { $this->io->writeError("Couldn't refresh access token: ".$e->getMessage()); return false; } $this->io->setAuthentication($originUrl, $response['access_token'], 'oauth2'); // store value in user config in auth file $this->config->getAuthConfigSource()->addConfigSetting( 'gitlab-oauth.'.$originUrl, [ 'expires-at' => intval($response['created_at']) + intval($response['expires_in']), 'refresh-token' => $response['refresh_token'], 'token' => $response['access_token'], ] ); return true; } /** * @return array{access_token: non-empty-string, refresh_token: non-empty-string, token_type: non-empty-string, expires_in?: positive-int, created_at: positive-int} * * @see https://docs.gitlab.com/ee/api/oauth2.html#resource-owner-password-credentials-flow */ private function createToken(string $scheme, string $originUrl): array { $username = $this->io->ask('Username: '); $password = $this->io->askAndHideAnswer('Password: '); $headers = ['Content-Type: application/x-www-form-urlencoded']; $apiUrl = $originUrl; $data = http_build_query([ 'username' => $username, 'password' => $password, 'grant_type' => 'password', ], '', '&'); $options = [ 'retry-auth-failure' => false, 'http' => [ 'method' => 'POST', 'header' => $headers, 'content' => $data, ], ]; $token = $this->httpDownloader->get($scheme.'://'.$apiUrl.'/oauth/token', $options)->decodeJson(); $this->io->writeError('Token successfully created'); return $token; } /** * Is the OAuth access token expired? * * @return bool true on expired token, false if token is fresh or expiration date is not set */ public function isOAuthExpired(string $originUrl): bool { $authTokens = $this->config->get('gitlab-oauth'); if (isset($authTokens[$originUrl]['expires-at'])) { if ($authTokens[$originUrl]['expires-at'] < time()) { return true; } } return false; } /** * @return array{access_token: non-empty-string, refresh_token: non-empty-string, token_type: non-empty-string, expires_in: positive-int, created_at: positive-int} * * @see https://docs.gitlab.com/ee/api/oauth2.html#resource-owner-password-credentials-flow */ private function refreshToken(string $scheme, string $originUrl): array { $authTokens = $this->config->get('gitlab-oauth'); if (!isset($authTokens[$originUrl]['refresh-token'])) { throw new \RuntimeException('No GitLab refresh token present for '.$originUrl.'.'); } $refreshToken = $authTokens[$originUrl]['refresh-token']; $headers = ['Content-Type: application/x-www-form-urlencoded']; $data = http_build_query([ 'refresh_token' => $refreshToken, 'grant_type' => 'refresh_token', ], '', '&'); $options = [ 'retry-auth-failure' => false, 'http' => [ 'method' => 'POST', 'header' => $headers, 'content' => $data, ], ]; $token = $this->httpDownloader->get($scheme.'://'.$originUrl.'/oauth/token', $options)->decodeJson(); $this->io->writeError('GitLab token successfully refreshed', true, IOInterface::VERY_VERBOSE); $this->io->writeError('To revoke access to this token you can visit '.$scheme.'://'.$originUrl.'/-/user_settings/applications', true, IOInterface::VERY_VERBOSE); return $token; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/ForgejoRepositoryData.php
src/Composer/Util/ForgejoRepositoryData.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\Util; /** * @internal * @readonly */ final class ForgejoRepositoryData { /** @var string */ public $htmlUrl; /** @var string */ public $sshUrl; /** @var string */ public $httpCloneUrl; /** @var bool */ public $isPrivate; /** @var string */ public $defaultBranch; /** @var bool */ public $hasIssues; /** @var bool */ public $isArchived; public function __construct( string $htmlUrl, string $httpCloneUrl, string $sshUrl, bool $isPrivate, string $defaultBranch, bool $hasIssues, bool $isArchived ) { $this->htmlUrl = $htmlUrl; $this->httpCloneUrl = $httpCloneUrl; $this->sshUrl = $sshUrl; $this->isPrivate = $isPrivate; $this->defaultBranch = $defaultBranch; $this->hasIssues = $hasIssues; $this->isArchived = $isArchived; } /** * @param array<string, mixed> $data */ public static function fromRemoteData(array $data): self { return new self( $data['html_url'], $data['clone_url'], $data['ssh_url'], $data['private'], $data['default_branch'], $data['has_issues'], $data['archived'] ); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Forgejo.php
src/Composer/Util/Forgejo.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\Util; use Composer\Config; use Composer\Downloader\TransportException; use Composer\IO\IOInterface; /** * @internal * @readonly */ final class Forgejo { /** @var IOInterface */ private $io; /** @var Config */ private $config; /** @var HttpDownloader */ private $httpDownloader; public function __construct(IOInterface $io, Config $config, HttpDownloader $httpDownloader) { $this->io = $io; $this->config = $config; $this->httpDownloader = $httpDownloader; } /** * Authorizes a Forgejo domain interactively * * @param string $originUrl The host this Forgejo instance is located at * @param string $message The reason this authorization is required * @throws \RuntimeException * @throws TransportException|\Exception * @return bool true on success */ public function authorizeOAuthInteractively(string $originUrl, ?string $message = null): bool { if ($message !== null) { $this->io->writeError($message); } $url = 'https://'.$originUrl.'/user/settings/applications'; $this->io->writeError('Setup a personal access token with repository:read permissions on:'); $this->io->writeError($url); $localAuthConfig = $this->config->getLocalAuthConfigSource(); $this->io->writeError(sprintf('Tokens will be stored in plain text in "%s" for future use by Composer.', ($localAuthConfig !== null ? $localAuthConfig->getName() . ' OR ' : '') . $this->config->getAuthConfigSource()->getName())); $this->io->writeError('For additional information, check https://getcomposer.org/doc/articles/authentication-for-private-packages.md#forgejo-token'); $storeInLocalAuthConfig = false; if ($localAuthConfig !== null) { $storeInLocalAuthConfig = $this->io->askConfirmation('A local auth config source was found, do you want to store the token there?', true); } $username = trim((string) $this->io->ask('Username: ')); $token = trim((string) $this->io->askAndHideAnswer('Token (hidden): ')); $addTokenManually = sprintf('You can also add it manually later by using "composer config --global --auth forgejo-token.%s <username> <token>"', $originUrl); if ($token === '' || $username === '') { $this->io->writeError('<warning>No username/token given, aborting.</warning>'); $this->io->writeError($addTokenManually); return false; } $this->io->setAuthentication($originUrl, $username, $token); try { $this->httpDownloader->get('https://'. $originUrl . '/api/v1/version', [ 'retry-auth-failure' => false, ]); } catch (TransportException $e) { if (in_array($e->getCode(), [403, 401, 404], true)) { $this->io->writeError('<error>Invalid access token provided.</error>'); $this->io->writeError($addTokenManually); return false; } throw $e; } // store value in local/user config $authConfigSource = $storeInLocalAuthConfig && $localAuthConfig !== null ? $localAuthConfig : $this->config->getAuthConfigSource(); $this->config->getConfigSource()->removeConfigSetting('forgejo-token.'.$originUrl); $authConfigSource->addConfigSetting('forgejo-token.'.$originUrl, ['username' => $username, 'token' => $token]); $this->io->writeError('<info>Token stored successfully.</info>'); return true; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/PackageInfo.php
src/Composer/Util/PackageInfo.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\Util; use Composer\Package\CompletePackageInterface; use Composer\Package\PackageInterface; class PackageInfo { public static function getViewSourceUrl(PackageInterface $package): ?string { if ($package instanceof CompletePackageInterface && isset($package->getSupport()['source']) && '' !== $package->getSupport()['source']) { return $package->getSupport()['source']; } return $package->getSourceUrl(); } public static function getViewSourceOrHomepageUrl(PackageInterface $package): ?string { $url = self::getViewSourceUrl($package) ?? ($package instanceof CompletePackageInterface ? $package->getHomepage() : null); if ($url === '') { return null; } return $url; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/AuthHelper.php
src/Composer/Util/AuthHelper.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\Util; use Composer\Config; use Composer\IO\IOInterface; use Composer\Downloader\TransportException; use Composer\Pcre\Preg; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class AuthHelper { /** @var IOInterface */ protected $io; /** @var Config */ protected $config; /** @var array<string, string> Map of origins to message displayed */ private $displayedOriginAuthentications = []; /** @var array<string, bool> Map of URLs and whether they already retried with authentication from Bitbucket */ private $bitbucketRetry = []; public function __construct(IOInterface $io, Config $config) { $this->io = $io; $this->config = $config; } /** * @param 'prompt'|bool $storeAuth */ public function storeAuth(string $origin, $storeAuth): void { $store = false; $configSource = $this->config->getAuthConfigSource(); if ($storeAuth === true) { $store = $configSource; } elseif ($storeAuth === 'prompt') { $answer = $this->io->askAndValidate( 'Do you want to store credentials for '.$origin.' in '.$configSource->getName().' ? [Yn] ', static function ($value): string { $input = strtolower(substr(trim($value), 0, 1)); if (in_array($input, ['y','n'])) { return $input; } throw new \RuntimeException('Please answer (y)es or (n)o'); }, null, 'y' ); if ($answer === 'y') { $store = $configSource; } } if ($store) { $store->addConfigSetting( 'http-basic.'.$origin, $this->io->getAuthentication($origin) ); } } /** * @param int $statusCode HTTP status code that triggered this call * @param string|null $reason a message/description explaining why this was called * @param string[] $headers * @param int $retryCount the amount of retries already done on this URL * @return array containing retry (bool) and storeAuth (string|bool) keys, if retry is true the request should be * retried, if storeAuth is true then on a successful retry the authentication should be persisted to auth.json * @phpstan-return array{retry: bool, storeAuth: 'prompt'|bool} */ public function promptAuthIfNeeded(string $url, string $origin, int $statusCode, ?string $reason = null, array $headers = [], int $retryCount = 0): array { $storeAuth = false; if (in_array($origin, $this->config->get('github-domains'), true)) { $gitHubUtil = new GitHub($this->io, $this->config, null); $message = "\n"; $rateLimited = $gitHubUtil->isRateLimited($headers); $requiresSso = $gitHubUtil->requiresSso($headers); if ($requiresSso) { $ssoUrl = $gitHubUtil->getSsoUrl($headers); $message = 'GitHub API token requires SSO authorization. Authorize this token at ' . $ssoUrl . "\n"; $this->io->writeError($message); if (!$this->io->isInteractive()) { throw new TransportException('Could not authenticate against ' . $origin, 403); } $this->io->ask('After authorizing your token, confirm that you would like to retry the request'); return ['retry' => true, 'storeAuth' => $storeAuth]; } if ($rateLimited) { $rateLimit = $gitHubUtil->getRateLimit($headers); if ($this->io->hasAuthentication($origin)) { $message = 'Review your configured GitHub OAuth token or enter a new one to go over the API rate limit.'; } else { $message = 'Create a GitHub OAuth token to go over the API rate limit.'; } $message = sprintf( 'GitHub API limit (%d calls/hr) is exhausted, could not fetch '.$url.'. '.$message.' You can also wait until %s for the rate limit to reset.', $rateLimit['limit'], $rateLimit['reset'] )."\n"; } else { $message .= 'Could not fetch '.$url.', please '; if ($this->io->hasAuthentication($origin)) { $message .= 'review your configured GitHub OAuth token or enter a new one to access private repos'; } else { $message .= 'create a GitHub OAuth token to access private repos'; } } if (!$gitHubUtil->authorizeOAuth($origin) && (!$this->io->isInteractive() || !$gitHubUtil->authorizeOAuthInteractively($origin, $message)) ) { throw new TransportException('Could not authenticate against '.$origin, 401); } } elseif (in_array($origin, $this->config->get('gitlab-domains'), true)) { $message = "\n".'Could not fetch '.$url.', enter your ' . $origin . ' credentials ' .($statusCode === 401 ? 'to access private repos' : 'to go over the API rate limit'); $gitLabUtil = new GitLab($this->io, $this->config, null); $auth = null; if ($this->io->hasAuthentication($origin)) { $auth = $this->io->getAuthentication($origin); if (in_array($auth['password'], ['gitlab-ci-token', 'private-token', 'oauth2'], true)) { throw new TransportException("Invalid credentials for '" . $url . "', aborting.", $statusCode); } } if (!$gitLabUtil->authorizeOAuth($origin) && (!$this->io->isInteractive() || !$gitLabUtil->authorizeOAuthInteractively(parse_url($url, PHP_URL_SCHEME), $origin, $message)) ) { throw new TransportException('Could not authenticate against '.$origin, 401); } if ($auth !== null && $this->io->hasAuthentication($origin)) { if ($auth === $this->io->getAuthentication($origin)) { throw new TransportException("Invalid credentials for '" . $url . "', aborting.", $statusCode); } } } elseif ($origin === 'bitbucket.org' || $origin === 'api.bitbucket.org') { $askForOAuthToken = true; $origin = 'bitbucket.org'; if ($this->io->hasAuthentication($origin)) { $auth = $this->io->getAuthentication($origin); if ($auth['username'] !== 'x-token-auth') { $bitbucketUtil = new Bitbucket($this->io, $this->config); $accessToken = $bitbucketUtil->requestToken($origin, $auth['username'], $auth['password']); if (!empty($accessToken)) { $this->io->setAuthentication($origin, 'x-token-auth', $accessToken); $askForOAuthToken = false; } } elseif (!isset($this->bitbucketRetry[$url])) { // when multiple requests fire at the same time, they will all fail and the first one resets the token to be correct above but then the others // reach the code path and without this fallback they would end up throwing below // see https://github.com/composer/composer/pull/11464 for more details $askForOAuthToken = false; $this->bitbucketRetry[$url] = true; } else { throw new TransportException('Could not authenticate against ' . $origin, 401); } } if ($askForOAuthToken) { $message = "\n".'Could not fetch ' . $url . ', please create a bitbucket OAuth token to ' . (($statusCode === 401 || $statusCode === 403) ? 'access private repos' : 'go over the API rate limit'); $bitBucketUtil = new Bitbucket($this->io, $this->config); if (!$bitBucketUtil->authorizeOAuth($origin) && (!$this->io->isInteractive() || !$bitBucketUtil->authorizeOAuthInteractively($origin, $message)) ) { throw new TransportException('Could not authenticate against ' . $origin, 401); } } } else { // 404s are only handled for github if ($statusCode === 404) { return ['retry' => false, 'storeAuth' => false]; } // fail if the console is not interactive if (!$this->io->isInteractive()) { if ($statusCode === 401) { $message = "The '" . $url . "' URL required authentication (HTTP 401).\nYou must be using the interactive console to authenticate"; } elseif ($statusCode === 403) { $message = "The '" . $url . "' URL could not be accessed (HTTP 403): " . $reason; } else { $message = "Unknown error code '" . $statusCode . "', reason: " . $reason; } throw new TransportException($message, $statusCode); } // fail if we already have auth if ($this->io->hasAuthentication($origin)) { // if two or more requests are started together for the same host, and the first // received authentication already, we let the others retry before failing them if ($retryCount === 0) { return ['retry' => true, 'storeAuth' => false]; } throw new TransportException("Invalid credentials (HTTP $statusCode) for '$url', aborting.", $statusCode); } $this->io->writeError(' Authentication required (<info>'.$origin.'</info>):'); $username = $this->io->ask(' Username: '); $password = $this->io->askAndHideAnswer(' Password: '); $this->io->setAuthentication($origin, $username, $password); $storeAuth = $this->config->get('store-auths'); } return ['retry' => true, 'storeAuth' => $storeAuth]; } /** * @deprecated use addAuthenticationOptions instead * * @param string[] $headers * * @return string[] updated headers array */ public function addAuthenticationHeader(array $headers, string $origin, string $url): array { trigger_error('AuthHelper::addAuthenticationHeader is deprecated since Composer 2.9 use addAuthenticationOptions instead.', E_USER_DEPRECATED); $options = ['http' => ['header' => &$headers]]; $options = $this->addAuthenticationOptions($options, $origin, $url); return $options['http']['header']; } /** * @param array<string, mixed> $options * * @return array<string, mixed> updated options */ public function addAuthenticationOptions(array $options, string $origin, string $url): array { if (!isset($options['http'])) { $options['http'] = []; } if (!isset($options['http']['header'])) { $options['http']['header'] = []; } $headers = &$options['http']['header']; if ($this->io->hasAuthentication($origin)) { $authenticationDisplayMessage = null; $auth = $this->io->getAuthentication($origin); if ($auth['password'] === 'bearer') { $headers[] = 'Authorization: Bearer '.$auth['username']; } elseif ($auth['password'] === 'custom-headers') { // Handle custom HTTP headers from auth.json $customHeaders = null; if (is_string($auth['username'])) { $customHeaders = json_decode($auth['username'], true); } if (is_array($customHeaders)) { foreach ($customHeaders as $header) { $headers[] = $header; } $authenticationDisplayMessage = 'Using custom HTTP headers for authentication'; } } elseif ('github.com' === $origin && 'x-oauth-basic' === $auth['password']) { // only add the access_token if it is actually a github API URL if (Preg::isMatch('{^https?://api\.github\.com/}', $url)) { $headers[] = 'Authorization: token '.$auth['username']; $authenticationDisplayMessage = 'Using GitHub token authentication'; } } elseif ( in_array($auth['password'], ['oauth2', 'private-token', 'gitlab-ci-token'], true) && in_array($origin, $this->config->get('gitlab-domains'), true) ) { if ($auth['password'] === 'oauth2') { $headers[] = 'Authorization: Bearer '.$auth['username']; $authenticationDisplayMessage = 'Using GitLab OAuth token authentication'; } else { $headers[] = 'PRIVATE-TOKEN: '.$auth['username']; $authenticationDisplayMessage = 'Using GitLab private token authentication'; } } elseif ( 'bitbucket.org' === $origin && $url !== Bitbucket::OAUTH2_ACCESS_TOKEN_URL && 'x-token-auth' === $auth['username'] ) { if (!$this->isPublicBitBucketDownload($url)) { $headers[] = 'Authorization: Bearer ' . $auth['password']; $authenticationDisplayMessage = 'Using Bitbucket OAuth token authentication'; } } elseif ('client-certificate' === $auth['username']) { $options['ssl'] = array_merge($options['ssl'] ?? [], json_decode((string) $auth['password'], true)); $authenticationDisplayMessage = 'Using SSL client certificate'; } else { $authStr = base64_encode($auth['username'] . ':' . $auth['password']); $headers[] = 'Authorization: Basic '.$authStr; $authenticationDisplayMessage = 'Using HTTP basic authentication with username "' . $auth['username'] . '"'; } if ($authenticationDisplayMessage && (!isset($this->displayedOriginAuthentications[$origin]) || $this->displayedOriginAuthentications[$origin] !== $authenticationDisplayMessage)) { $this->io->writeError($authenticationDisplayMessage, true, IOInterface::DEBUG); $this->displayedOriginAuthentications[$origin] = $authenticationDisplayMessage; } } elseif (in_array($origin, ['api.bitbucket.org', 'api.github.com'], true)) { return $this->addAuthenticationOptions($options, str_replace('api.', '', $origin), $url); } return $options; } /** * @link https://github.com/composer/composer/issues/5584 * * @param string $urlToBitBucketFile URL to a file at bitbucket.org. * * @return bool Whether the given URL is a public BitBucket download which requires no authentication. */ public function isPublicBitBucketDownload(string $urlToBitBucketFile): bool { $domain = parse_url($urlToBitBucketFile, PHP_URL_HOST); if (strpos($domain, 'bitbucket.org') === false) { // Bitbucket downloads are hosted on amazonaws. // We do not need to authenticate there at all return true; } $path = parse_url($urlToBitBucketFile, PHP_URL_PATH); // Path for a public download follows this pattern /{user}/{repo}/downloads/{whatever} // {@link https://blog.bitbucket.org/2009/04/12/new-feature-downloads/} $pathParts = explode('/', $path); return count($pathParts) >= 4 && $pathParts[3] === 'downloads'; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Zip.php
src/Composer/Util/Zip.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\Util; /** * @author Andreas Schempp <andreas.schempp@terminal42.ch> */ class Zip { /** * Gets content of the root composer.json inside a ZIP archive. */ public static function getComposerJson(string $pathToZip): ?string { if (!extension_loaded('zip')) { throw new \RuntimeException('The Zip Util requires PHP\'s zip extension'); } $zip = new \ZipArchive(); if ($zip->open($pathToZip) !== true) { return null; } if (0 === $zip->numFiles) { $zip->close(); return null; } $foundFileIndex = self::locateFile($zip, 'composer.json'); $content = null; $configurationFileName = $zip->getNameIndex($foundFileIndex); $stream = $zip->getStream($configurationFileName); if (false !== $stream) { $content = stream_get_contents($stream); } $zip->close(); return $content; } /** * Find a file by name, returning the one that has the shortest path. * * @throws \RuntimeException */ private static function locateFile(\ZipArchive $zip, string $filename): int { // return root composer.json if it is there and is a file if (false !== ($index = $zip->locateName($filename)) && $zip->getFromIndex($index) !== false) { return $index; } $topLevelPaths = []; for ($i = 0; $i < $zip->numFiles; $i++) { $name = $zip->getNameIndex($i); $dirname = dirname($name); // ignore OSX specific resource fork folder if (strpos($name, '__MACOSX') !== false) { continue; } // handle archives with proper TOC if ($dirname === '.') { $topLevelPaths[$name] = true; if (\count($topLevelPaths) > 1) { throw new \RuntimeException('Archive has more than one top level directories, and no composer.json was found on the top level, so it\'s an invalid archive. Top level paths found were: '.implode(',', array_keys($topLevelPaths))); } continue; } // handle archives which do not have a TOC record for the directory itself if (false === strpos($dirname, '\\') && false === strpos($dirname, '/')) { $topLevelPaths[$dirname.'/'] = true; if (\count($topLevelPaths) > 1) { throw new \RuntimeException('Archive has more than one top level directories, and no composer.json was found on the top level, so it\'s an invalid archive. Top level paths found were: '.implode(',', array_keys($topLevelPaths))); } } } if ($topLevelPaths && false !== ($index = $zip->locateName(key($topLevelPaths).$filename)) && $zip->getFromIndex($index) !== false) { return $index; } throw new \RuntimeException('No composer.json found either at the top level or within the topmost directory'); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/PackageSorter.php
src/Composer/Util/PackageSorter.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\Util; use Composer\Package\PackageInterface; use Composer\Package\RootPackageInterface; class PackageSorter { /** * Returns the most recent version of a set of packages * * This is ideally the default branch version, or failing that it will return the package with the highest version * * @template T of PackageInterface * @param array<T> $packages * @return ($packages is non-empty-array<T> ? T : T|null) */ public static function getMostCurrentVersion(array $packages): ?PackageInterface { if (count($packages) === 0) { return null; } $highest = reset($packages); foreach ($packages as $candidate) { if ($candidate->isDefaultBranch()) { return $candidate; } if (version_compare($highest->getVersion(), $candidate->getVersion(), '<')) { $highest = $candidate; } } return $highest; } /** * Sorts packages by name * * @template T of PackageInterface * @param array<T> $packages * @return array<T> */ public static function sortPackagesAlphabetically(array $packages): array { usort($packages, static function (PackageInterface $a, PackageInterface $b) { return $a->getName() <=> $b->getName(); }); return $packages; } /** * Sorts packages by dependency weight * * Packages of equal weight are sorted alphabetically * * @param PackageInterface[] $packages * @param array<string, int> $weights Pre-set weights for some packages to give them more (negative number) or less (positive) weight offsets * @return PackageInterface[] sorted array */ public static function sortPackages(array $packages, array $weights = []): array { $usageList = []; foreach ($packages as $package) { $links = $package->getRequires(); if ($package instanceof RootPackageInterface) { $links = array_merge($links, $package->getDevRequires()); } foreach ($links as $link) { $target = $link->getTarget(); $usageList[$target][] = $package->getName(); } } $computing = []; $computed = []; $computeImportance = static function ($name) use (&$computeImportance, &$computing, &$computed, $usageList, $weights) { // reusing computed importance if (isset($computed[$name])) { return $computed[$name]; } // canceling circular dependency if (isset($computing[$name])) { return 0; } $computing[$name] = true; $weight = $weights[$name] ?? 0; if (isset($usageList[$name])) { foreach ($usageList[$name] as $user) { $weight -= 1 - $computeImportance($user); } } unset($computing[$name]); $computed[$name] = $weight; return $weight; }; $weightedPackages = []; foreach ($packages as $index => $package) { $name = $package->getName(); $weight = $computeImportance($name); $weightedPackages[] = ['name' => $name, 'weight' => $weight, 'index' => $index]; } usort($weightedPackages, static function (array $a, array $b): int { if ($a['weight'] !== $b['weight']) { return $a['weight'] - $b['weight']; } return strnatcasecmp($a['name'], $b['name']); }); $sortedPackages = []; foreach ($weightedPackages as $pkg) { $sortedPackages[] = $packages[$pkg['index']]; } return $sortedPackages; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Http/ProxyManager.php
src/Composer/Util/Http/ProxyManager.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\Util\Http; use Composer\Downloader\TransportException; use Composer\Util\NoProxyPattern; /** * @internal * @author John Stevenson <john-stevenson@blueyonder.co.uk> */ class ProxyManager { /** @var ?string */ private $error = null; /** @var ?ProxyItem */ private $httpProxy = null; /** @var ?ProxyItem */ private $httpsProxy = null; /** @var ?NoProxyPattern */ private $noProxyHandler = null; /** @var ?self */ private static $instance = null; private function __construct() { try { $this->getProxyData(); } catch (\RuntimeException $e) { $this->error = $e->getMessage(); } } public static function getInstance(): ProxyManager { if (self::$instance === null) { self::$instance = new self(); } return self::$instance; } /** * Clears the persistent instance */ public static function reset(): void { self::$instance = null; } public function hasProxy(): bool { return $this->httpProxy !== null || $this->httpsProxy !== null; } /** * Returns a RequestProxy instance for the request url * * @param non-empty-string $requestUrl */ public function getProxyForRequest(string $requestUrl): RequestProxy { if ($this->error !== null) { throw new TransportException('Unable to use a proxy: '.$this->error); } $scheme = (string) parse_url($requestUrl, PHP_URL_SCHEME); $proxy = $this->getProxyForScheme($scheme); if ($proxy === null) { return RequestProxy::none(); } if ($this->noProxy($requestUrl)) { return RequestProxy::noProxy(); } return $proxy->toRequestProxy($scheme); } /** * Returns a ProxyItem if one is set for the scheme, otherwise null */ private function getProxyForScheme(string $scheme): ?ProxyItem { if ($scheme === 'http') { return $this->httpProxy; } if ($scheme === 'https') { return $this->httpsProxy; } return null; } /** * Finds proxy values from the environment and sets class properties */ private function getProxyData(): void { // Handle http_proxy/HTTP_PROXY on CLI only for security reasons if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { [$env, $name] = $this->getProxyEnv('http_proxy'); if ($env !== null) { $this->httpProxy = new ProxyItem($env, $name); } } // Handle cgi_http_proxy/CGI_HTTP_PROXY if needed if ($this->httpProxy === null) { [$env, $name] = $this->getProxyEnv('cgi_http_proxy'); if ($env !== null) { $this->httpProxy = new ProxyItem($env, $name); } } // Handle https_proxy/HTTPS_PROXY [$env, $name] = $this->getProxyEnv('https_proxy'); if ($env !== null) { $this->httpsProxy = new ProxyItem($env, $name); } // Handle no_proxy/NO_PROXY [$env, $name] = $this->getProxyEnv('no_proxy'); if ($env !== null) { $this->noProxyHandler = new NoProxyPattern($env); } } /** * Searches $_SERVER for case-sensitive values * * @return array{0: string|null, 1: string} value, name */ private function getProxyEnv(string $envName): array { $names = [strtolower($envName), strtoupper($envName)]; foreach ($names as $name) { if (is_string($_SERVER[$name] ?? null)) { if ($_SERVER[$name] !== '') { return [$_SERVER[$name], $name]; } } } return [null, '']; } /** * Returns true if a url matches no_proxy value */ private function noProxy(string $requestUrl): bool { if ($this->noProxyHandler === null) { return false; } return $this->noProxyHandler->test($requestUrl); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Http/Response.php
src/Composer/Util/Http/Response.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\Util\Http; use Composer\Json\JsonFile; use Composer\Pcre\Preg; /** * @phpstan-type Request array{url: non-empty-string, options?: mixed[], copyTo?: string|null} */ class Response { /** @var Request */ private $request; /** @var int */ private $code; /** @var list<string> */ private $headers; /** @var ?string */ private $body; /** * @param Request $request * @param list<string> $headers */ public function __construct(array $request, ?int $code, array $headers, ?string $body) { if (!isset($request['url'])) { throw new \LogicException('url key missing from request array'); } $this->request = $request; $this->code = (int) $code; $this->headers = $headers; $this->body = $body; } public function getStatusCode(): int { return $this->code; } public function getStatusMessage(): ?string { $value = null; foreach ($this->headers as $header) { if (Preg::isMatch('{^HTTP/\S+ \d+}i', $header)) { // In case of redirects, headers contain the headers of all responses // so we can not return directly and need to keep iterating $value = $header; } } return $value; } /** * @return string[] */ public function getHeaders(): array { return $this->headers; } public function getHeader(string $name): ?string { return self::findHeaderValue($this->headers, $name); } public function getBody(): ?string { return $this->body; } /** * @return mixed */ public function decodeJson() { return JsonFile::parseJson($this->body, $this->request['url']); } /** * @phpstan-impure */ public function collect(): void { unset($this->request, $this->code, $this->headers, $this->body); } /** * @param string[] $headers array of returned headers like from getLastHeaders() * @param string $name header name (case insensitive) */ public static function findHeaderValue(array $headers, string $name): ?string { $value = null; foreach ($headers as $header) { if (Preg::isMatch('{^'.preg_quote($name).':\s*(.+?)\s*$}i', $header, $match)) { $value = $match[1]; } } return $value; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Http/ProxyItem.php
src/Composer/Util/Http/ProxyItem.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\Util\Http; /** * @internal * @author John Stevenson <john-stevenson@blueyonder.co.uk> */ class ProxyItem { /** @var non-empty-string */ private $url; /** @var non-empty-string */ private $safeUrl; /** @var ?non-empty-string */ private $curlAuth; /** @var string */ private $optionsProxy; /** @var ?non-empty-string */ private $optionsAuth; /** * @param string $proxyUrl The value from the environment * @param string $envName The name of the environment variable * @throws \RuntimeException If the proxy url is invalid */ public function __construct(string $proxyUrl, string $envName) { $syntaxError = sprintf('unsupported `%s` syntax', $envName); if (strpbrk($proxyUrl, "\r\n\t") !== false) { throw new \RuntimeException($syntaxError); } if (false === ($proxy = parse_url($proxyUrl))) { throw new \RuntimeException($syntaxError); } if (!isset($proxy['host'])) { throw new \RuntimeException('unable to find proxy host in ' . $envName); } $scheme = isset($proxy['scheme']) ? strtolower($proxy['scheme']) . '://' : 'http://'; $safe = ''; if (isset($proxy['user'])) { $safe = '***'; $user = $proxy['user']; $auth = rawurldecode($proxy['user']); if (isset($proxy['pass'])) { $safe .= ':***'; $user .= ':' . $proxy['pass']; $auth .= ':' . rawurldecode($proxy['pass']); } $safe .= '@'; if (strlen($user) > 0) { $this->curlAuth = $user; $this->optionsAuth = 'Proxy-Authorization: Basic ' . base64_encode($auth); } } $host = $proxy['host']; $port = null; if (isset($proxy['port'])) { $port = $proxy['port']; } elseif ($scheme === 'http://') { $port = 80; } elseif ($scheme === 'https://') { $port = 443; } // We need a port because curl uses 1080 for http. Port 0 is reserved, // but is considered valid depending on the PHP or Curl version. if ($port === null) { throw new \RuntimeException('unable to find proxy port in ' . $envName); } if ($port === 0) { throw new \RuntimeException('port 0 is reserved in ' . $envName); } $this->url = sprintf('%s%s:%d', $scheme, $host, $port); $this->safeUrl = sprintf('%s%s%s:%d', $scheme, $safe, $host, $port); $scheme = str_replace(['http://', 'https://'], ['tcp://', 'ssl://'], $scheme); $this->optionsProxy = sprintf('%s%s:%d', $scheme, $host, $port); } /** * Returns a RequestProxy instance for the scheme of the request url * * @param string $scheme The scheme of the request url */ public function toRequestProxy(string $scheme): RequestProxy { $options = ['http' => ['proxy' => $this->optionsProxy]]; if ($this->optionsAuth !== null) { $options['http']['header'] = $this->optionsAuth; } if ($scheme === 'http') { $options['http']['request_fulluri'] = true; } return new RequestProxy($this->url, $this->curlAuth, $options, $this->safeUrl); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Http/RequestProxy.php
src/Composer/Util/Http/RequestProxy.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\Util\Http; use Composer\Downloader\TransportException; /** * @internal * @author John Stevenson <john-stevenson@blueyonder.co.uk> * * @phpstan-type contextOptions array{http: array{proxy: string, header?: string, request_fulluri?: bool}} */ class RequestProxy { /** @var ?contextOptions */ private $contextOptions; /** @var ?non-empty-string */ private $status; /** @var ?non-empty-string */ private $url; /** @var ?non-empty-string */ private $auth; /** * @param ?non-empty-string $url The proxy url, without authorization * @param ?non-empty-string $auth Authorization for curl * @param ?contextOptions $contextOptions * @param ?non-empty-string $status */ public function __construct(?string $url, ?string $auth, ?array $contextOptions, ?string $status) { $this->url = $url; $this->auth = $auth; $this->contextOptions = $contextOptions; $this->status = $status; } public static function none(): RequestProxy { return new self(null, null, null, null); } public static function noProxy(): RequestProxy { return new self(null, null, null, 'excluded by no_proxy'); } /** * Returns the context options to use for this request, otherwise null * * @return ?contextOptions */ public function getContextOptions(): ?array { return $this->contextOptions; } /** * Returns an array of curl proxy options * * @param array<string, string|int> $sslOptions * @return array<int, string|int> */ public function getCurlOptions(array $sslOptions): array { if ($this->isSecure() && !$this->supportsSecureProxy()) { throw new TransportException('Cannot use an HTTPS proxy. PHP >= 7.3 and cUrl >= 7.52.0 are required.'); } // Always set a proxy url, even an empty value, because it tells curl // to ignore proxy environment variables $options = [CURLOPT_PROXY => (string) $this->url]; // If using a proxy, tell curl to ignore no_proxy environment variables if ($this->url !== null) { $options[CURLOPT_NOPROXY] = ''; } // Set any authorization if ($this->auth !== null) { $options[CURLOPT_PROXYAUTH] = CURLAUTH_BASIC; $options[CURLOPT_PROXYUSERPWD] = $this->auth; } if ($this->isSecure()) { if (isset($sslOptions['cafile'])) { $options[CURLOPT_PROXY_CAINFO] = $sslOptions['cafile']; } if (isset($sslOptions['capath'])) { $options[CURLOPT_PROXY_CAPATH] = $sslOptions['capath']; } } return $options; } /** * Returns proxy info associated with this request * * An empty return value means that the user has not set a proxy. * A non-empty value will either be the sanitized proxy url if a proxy is * required, or a message indicating that a no_proxy value has disabled the * proxy. * * @param ?string $format Output format specifier */ public function getStatus(?string $format = null): string { if ($this->status === null) { return ''; } $format = $format ?? '%s'; if (strpos($format, '%s') !== false) { return sprintf($format, $this->status); } throw new \InvalidArgumentException('String format specifier is missing'); } /** * Returns true if the request url has been excluded by a no_proxy value * * A false value can also mean that the user has not set a proxy. */ public function isExcludedByNoProxy(): bool { return $this->status !== null && $this->url === null; } /** * Returns true if this is a secure (HTTPS) proxy * * A false value means that this is either an HTTP proxy, or that a proxy * is not required for this request, or that the user has not set a proxy. */ public function isSecure(): bool { return 0 === strpos((string) $this->url, 'https://'); } /** * Returns true if an HTTPS proxy can be used. * * This depends on PHP7.3+ for CURL_VERSION_HTTPS_PROXY * and curl including the feature (from version 7.52.0) */ public function supportsSecureProxy(): bool { if (false === ($version = curl_version()) || !defined('CURL_VERSION_HTTPS_PROXY')) { return false; } $features = $version['features']; return (bool) ($features & CURL_VERSION_HTTPS_PROXY); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Http/CurlDownloader.php
src/Composer/Util/Http/CurlDownloader.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\Util\Http; use Composer\Config; use Composer\Downloader\MaxFileSizeExceededException; use Composer\IO\IOInterface; use Composer\Downloader\TransportException; use Composer\Pcre\Preg; use Composer\Util\Platform; use Composer\Util\StreamContextFactory; use Composer\Util\AuthHelper; use Composer\Util\Url; use Composer\Util\HttpDownloader; use React\Promise\Promise; /** * @internal * @author Jordi Boggiano <j.boggiano@seld.be> * @author Nicolas Grekas <p@tchwork.com> * @phpstan-type Attributes array{retryAuthFailure: bool, redirects: int<0, max>, retries: int<0, max>, storeAuth: 'prompt'|bool, ipResolve: 4|6|null} * @phpstan-type Job array{url: non-empty-string, origin: string, attributes: Attributes, options: mixed[], progress: mixed[], curlHandle: \CurlHandle, filename: string|null, headerHandle: resource, bodyHandle: resource, resolve: callable, reject: callable, primaryIp: string} */ class CurlDownloader { /** * Known libcurl's broken versions when proxy is in use with HTTP/2 * multiplexing. * * @var list<non-empty-string> */ private const BAD_MULTIPLEXING_CURL_VERSIONS = ['7.87.0', '7.88.0', '7.88.1']; /** @var \CurlMultiHandle */ private $multiHandle; /** @var \CurlShareHandle */ private $shareHandle; /** @var Job[] */ private $jobs = []; /** @var IOInterface */ private $io; /** @var Config */ private $config; /** @var AuthHelper */ private $authHelper; /** @var float */ private $selectTimeout = 5.0; /** @var int */ private $maxRedirects = 20; /** @var int */ private $maxRetries = 3; /** @var array<int, string[]> */ protected $multiErrors = [ CURLM_BAD_HANDLE => ['CURLM_BAD_HANDLE', 'The passed-in handle is not a valid CURLM handle.'], CURLM_BAD_EASY_HANDLE => ['CURLM_BAD_EASY_HANDLE', "An easy handle was not good/valid. It could mean that it isn't an easy handle at all, or possibly that the handle already is in used by this or another multi handle."], CURLM_OUT_OF_MEMORY => ['CURLM_OUT_OF_MEMORY', 'You are doomed.'], CURLM_INTERNAL_ERROR => ['CURLM_INTERNAL_ERROR', 'This can only be returned if libcurl bugs. Please report it to us!'], ]; /** @var mixed[] */ private static $options = [ 'http' => [ 'method' => CURLOPT_CUSTOMREQUEST, 'content' => CURLOPT_POSTFIELDS, 'header' => CURLOPT_HTTPHEADER, 'timeout' => CURLOPT_TIMEOUT, ], 'ssl' => [ 'cafile' => CURLOPT_CAINFO, 'capath' => CURLOPT_CAPATH, 'verify_peer' => CURLOPT_SSL_VERIFYPEER, 'verify_peer_name' => CURLOPT_SSL_VERIFYHOST, 'local_cert' => CURLOPT_SSLCERT, 'local_pk' => CURLOPT_SSLKEY, 'passphrase' => CURLOPT_SSLKEYPASSWD, ], ]; /** @var array<string, true> */ private static $timeInfo = [ 'total_time' => true, 'namelookup_time' => true, 'connect_time' => true, 'pretransfer_time' => true, 'starttransfer_time' => true, 'redirect_time' => true, ]; /** * @param mixed[] $options */ public function __construct(IOInterface $io, Config $config, array $options = [], bool $disableTls = false) { $this->io = $io; $this->config = $config; $this->multiHandle = $mh = curl_multi_init(); if (function_exists('curl_multi_setopt')) { if (ProxyManager::getInstance()->hasProxy() && ($version = curl_version()) !== false && in_array($version['version'], self::BAD_MULTIPLEXING_CURL_VERSIONS, true)) { /** * Disable HTTP/2 multiplexing for some broken versions of libcurl. * * In certain versions of libcurl when proxy is in use with HTTP/2 * multiplexing, connections will continue stacking up. This was * fixed in libcurl 8.0.0 in curl/curl@821f6e2a89de8aec1c7da3c0f381b92b2b801efc */ curl_multi_setopt($mh, CURLMOPT_PIPELINING, /* CURLPIPE_NOTHING */ 0); } else { curl_multi_setopt($mh, CURLMOPT_PIPELINING, \PHP_VERSION_ID >= 70400 ? /* CURLPIPE_MULTIPLEX */ 2 : /*CURLPIPE_HTTP1 | CURLPIPE_MULTIPLEX*/ 3); } if (defined('CURLMOPT_MAX_HOST_CONNECTIONS') && !defined('HHVM_VERSION')) { curl_multi_setopt($mh, CURLMOPT_MAX_HOST_CONNECTIONS, 8); } } if (function_exists('curl_share_init')) { $this->shareHandle = $sh = curl_share_init(); curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE); curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS); curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION); } $this->authHelper = new AuthHelper($io, $config); } /** * @param mixed[] $options * @param non-empty-string $url * * @return int internal job id */ public function download(callable $resolve, callable $reject, string $origin, string $url, array $options, ?string $copyTo = null): int { $attributes = []; if (isset($options['retry-auth-failure'])) { $attributes['retryAuthFailure'] = $options['retry-auth-failure']; unset($options['retry-auth-failure']); } return $this->initDownload($resolve, $reject, $origin, $url, $options, $copyTo, $attributes); } /** * @param mixed[] $options * * @param array{retryAuthFailure?: bool, redirects?: int<0, max>, retries?: int<0, max>, storeAuth?: 'prompt'|bool, ipResolve?: 4|6|null} $attributes * @param non-empty-string $url * * @return int internal job id */ private function initDownload(callable $resolve, callable $reject, string $origin, string $url, array $options, ?string $copyTo = null, array $attributes = []): int { $attributes = array_merge([ 'retryAuthFailure' => true, 'redirects' => 0, 'retries' => 0, 'storeAuth' => false, 'ipResolve' => null, ], $attributes); if ($attributes['ipResolve'] === null && Platform::getEnv('COMPOSER_IPRESOLVE') === '4') { $attributes['ipResolve'] = 4; } elseif ($attributes['ipResolve'] === null && Platform::getEnv('COMPOSER_IPRESOLVE') === '6') { $attributes['ipResolve'] = 6; } $originalOptions = $options; // check URL can be accessed (i.e. is not insecure), but allow insecure Packagist calls to $hashed providers as file integrity is verified with sha256 if (!Preg::isMatch('{^http://(repo\.)?packagist\.org/p/}', $url) || (false === strpos($url, '$') && false === strpos($url, '%24'))) { $this->config->prohibitUrlByConfig($url, $this->io, $options); } $curlHandle = curl_init(); $headerHandle = fopen('php://temp/maxmemory:32768', 'w+b'); if (false === $headerHandle) { throw new \RuntimeException('Failed to open a temp stream to store curl headers'); } if ($copyTo !== null) { $bodyTarget = $copyTo.'~'; } else { $bodyTarget = 'php://temp/maxmemory:524288'; } $errorMessage = ''; set_error_handler(static function (int $code, string $msg) use (&$errorMessage): bool { if ($errorMessage) { $errorMessage .= "\n"; } $errorMessage .= Preg::replace('{^fopen\(.*?\): }', '', $msg); return true; }); $bodyHandle = fopen($bodyTarget, 'w+b'); restore_error_handler(); if (false === $bodyHandle) { throw new TransportException('The "'.$url.'" file could not be written to '.($copyTo ?? 'a temporary file').': '.$errorMessage); } curl_setopt($curlHandle, CURLOPT_URL, $url); curl_setopt($curlHandle, CURLOPT_FOLLOWLOCATION, false); curl_setopt($curlHandle, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($curlHandle, CURLOPT_TIMEOUT, max((int) ini_get("default_socket_timeout"), 300)); curl_setopt($curlHandle, CURLOPT_WRITEHEADER, $headerHandle); curl_setopt($curlHandle, CURLOPT_FILE, $bodyHandle); curl_setopt($curlHandle, CURLOPT_ENCODING, ""); // let cURL set the Accept-Encoding header to what it supports curl_setopt($curlHandle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS); if ($attributes['ipResolve'] === 4) { curl_setopt($curlHandle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); } elseif ($attributes['ipResolve'] === 6) { curl_setopt($curlHandle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6); } if (function_exists('curl_share_init')) { curl_setopt($curlHandle, CURLOPT_SHARE, $this->shareHandle); } if (!isset($options['http']['header'])) { $options['http']['header'] = []; } $options['http']['header'] = array_diff($options['http']['header'], ['Connection: close']); $options['http']['header'][] = 'Connection: keep-alive'; $version = curl_version(); $features = $version['features']; $proxy = ProxyManager::getInstance()->getProxyForRequest($url); if (0 === strpos($url, 'https://')) { $willUseProxy = $proxy->getStatus() !== '' && !$proxy->isExcludedByNoProxy(); if (!$willUseProxy && \defined('CURL_VERSION_HTTP3') && \defined('CURL_HTTP_VERSION_3') && (CURL_VERSION_HTTP3 & $features) !== 0) { curl_setopt($curlHandle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_3); } elseif (\defined('CURL_VERSION_HTTP2') && \defined('CURL_HTTP_VERSION_2_0') && (CURL_VERSION_HTTP2 & $features) !== 0) { curl_setopt($curlHandle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); } } // curl 8.7.0 - 8.7.1 has a bug whereas automatic accept-encoding header results in an error when reading the response // https://github.com/composer/composer/issues/11913 if (isset($version['version']) && in_array($version['version'], ['8.7.0', '8.7.1'], true) && \defined('CURL_VERSION_LIBZ') && (CURL_VERSION_LIBZ & $features) !== 0) { curl_setopt($curlHandle, CURLOPT_ENCODING, "gzip"); } $options = $this->authHelper->addAuthenticationOptions($options, $origin, $url); $options = StreamContextFactory::initOptions($url, $options, true); foreach (self::$options as $type => $curlOptions) { foreach ($curlOptions as $name => $curlOption) { if (isset($options[$type][$name])) { if ($type === 'ssl' && $name === 'verify_peer_name') { curl_setopt($curlHandle, $curlOption, $options[$type][$name] === true ? 2 : $options[$type][$name]); } else { curl_setopt($curlHandle, $curlOption, $options[$type][$name]); } } } } curl_setopt_array($curlHandle, $proxy->getCurlOptions($options['ssl'] ?? [])); $progress = array_diff_key(curl_getinfo($curlHandle), self::$timeInfo); $this->jobs[(int) $curlHandle] = [ 'url' => $url, 'origin' => $origin, 'attributes' => $attributes, 'options' => $originalOptions, 'progress' => $progress, 'curlHandle' => $curlHandle, 'filename' => $copyTo, 'headerHandle' => $headerHandle, 'bodyHandle' => $bodyHandle, 'resolve' => $resolve, 'reject' => $reject, 'primaryIp' => '', ]; $usingProxy = $proxy->getStatus(' using proxy (%s)'); $ifModified = false !== stripos(implode(',', $options['http']['header']), 'if-modified-since:') ? ' if modified' : ''; if ($attributes['redirects'] === 0 && $attributes['retries'] === 0) { $this->io->writeError('Downloading ' . Url::sanitize($url) . $usingProxy . $ifModified, true, IOInterface::DEBUG); } $this->checkCurlResult(curl_multi_add_handle($this->multiHandle, $curlHandle)); // TODO progress return (int) $curlHandle; } public function abortRequest(int $id): void { if (isset($this->jobs[$id], $this->jobs[$id]['curlHandle'])) { $job = $this->jobs[$id]; curl_multi_remove_handle($this->multiHandle, $job['curlHandle']); if (\PHP_VERSION_ID < 80000) { curl_close($job['curlHandle']); } if (is_resource($job['headerHandle'])) { fclose($job['headerHandle']); } if (is_resource($job['bodyHandle'])) { fclose($job['bodyHandle']); } if (null !== $job['filename']) { @unlink($job['filename'].'~'); } unset($this->jobs[$id]); } } public function tick(): void { static $timeoutWarning = false; if (count($this->jobs) === 0) { return; } $active = true; $this->checkCurlResult(curl_multi_exec($this->multiHandle, $active)); if (-1 === curl_multi_select($this->multiHandle, $this->selectTimeout)) { // sleep in case select returns -1 as it can happen on old php versions or some platforms where curl does not manage to do the select usleep(150); } while ($progress = curl_multi_info_read($this->multiHandle)) { $curlHandle = $progress['handle']; $result = $progress['result']; $i = (int) $curlHandle; if (!isset($this->jobs[$i])) { continue; } $progress = curl_getinfo($curlHandle); if (false === $progress) { throw new \RuntimeException('Failed getting info from curl handle '.$i.' ('.$this->jobs[$i]['url'].')'); } $job = $this->jobs[$i]; unset($this->jobs[$i]); $error = curl_error($curlHandle); $errno = curl_errno($curlHandle); curl_multi_remove_handle($this->multiHandle, $curlHandle); if (\PHP_VERSION_ID < 80000) { curl_close($curlHandle); } $headers = null; $statusCode = null; $response = null; try { // TODO progress if (CURLE_OK !== $errno || $error || $result !== CURLE_OK) { $errno = $errno ?: $result; if (!$error && function_exists('curl_strerror')) { $error = curl_strerror($errno); } $progress['error_code'] = $errno; if ($errno === 28 /* CURLE_OPERATION_TIMEDOUT */ && \PHP_VERSION_ID >= 70300 && $progress['namelookup_time'] === 0.0 && !$timeoutWarning) { $timeoutWarning = true; $this->io->writeError('<warning>A connection timeout was encountered. If you intend to run Composer without connecting to the internet, run the command again prefixed with COMPOSER_DISABLE_NETWORK=1 to make Composer run in offline mode.</warning>'); } if ( (!isset($job['options']['http']['method']) || $job['options']['http']['method'] === 'GET') && ( in_array($errno, [7 /* CURLE_COULDNT_CONNECT */, 16 /* CURLE_HTTP2 */, 92 /* CURLE_HTTP2_STREAM */, 6 /* CURLE_COULDNT_RESOLVE_HOST */, 28 /* CURLE_OPERATION_TIMEDOUT */], true) || (in_array($errno, [56 /* CURLE_RECV_ERROR */, 35 /* CURLE_SSL_CONNECT_ERROR */], true) && str_contains((string) $error, 'Connection reset by peer')) ) && $job['attributes']['retries'] < $this->maxRetries ) { $attributes = ['retries' => $job['attributes']['retries'] + 1]; if ($errno === 7 && !isset($job['attributes']['ipResolve'])) { // CURLE_COULDNT_CONNECT, retry forcing IPv4 if no IP stack was selected $attributes['ipResolve'] = 4; } $this->io->writeError('Retrying ('.($job['attributes']['retries'] + 1).') ' . Url::sanitize($job['url']) . ' due to curl error '. $errno, true, IOInterface::DEBUG); $this->restartJobWithDelay($job, $job['url'], $attributes); continue; } // TODO: Remove this as soon as https://github.com/curl/curl/issues/10591 is resolved if ($errno === 55 /* CURLE_SEND_ERROR */) { $this->io->writeError('Retrying ('.($job['attributes']['retries'] + 1).') ' . Url::sanitize($job['url']) . ' due to curl error '. $errno, true, IOInterface::DEBUG); $this->restartJobWithDelay($job, $job['url'], ['retries' => $job['attributes']['retries'] + 1]); continue; } throw new TransportException('curl error '.$errno.' while downloading '.Url::sanitize($progress['url']).': '.$error); } $statusCode = $progress['http_code']; rewind($job['headerHandle']); $headers = explode("\r\n", rtrim(stream_get_contents($job['headerHandle']))); fclose($job['headerHandle']); if ($statusCode === 0) { throw new \LogicException('Received unexpected http status code 0 without error for '.Url::sanitize($progress['url']).': headers '.var_export($headers, true).' curl info '.var_export($progress, true)); } // prepare response object if (null !== $job['filename']) { $contents = $job['filename'].'~'; if ($statusCode >= 300) { rewind($job['bodyHandle']); $contents = stream_get_contents($job['bodyHandle']); } $response = new CurlResponse(['url' => $job['url']], $statusCode, $headers, $contents, $progress); $this->io->writeError('['.$statusCode.'] '.Url::sanitize($job['url']), true, IOInterface::DEBUG); } else { $maxFileSize = $job['options']['max_file_size'] ?? null; rewind($job['bodyHandle']); if ($maxFileSize !== null) { $contents = stream_get_contents($job['bodyHandle'], $maxFileSize); // Gzipped responses with missing Content-Length header cannot be detected during the file download // because $progress['size_download'] refers to the gzipped size downloaded, not the actual file size if ($contents !== false && Platform::strlen($contents) >= $maxFileSize) { throw new MaxFileSizeExceededException('Maximum allowed download size reached. Downloaded ' . Platform::strlen($contents) . ' of allowed ' . $maxFileSize . ' bytes'); } } else { $contents = stream_get_contents($job['bodyHandle']); } $response = new CurlResponse(['url' => $job['url']], $statusCode, $headers, $contents, $progress); $this->io->writeError('['.$statusCode.'] '.Url::sanitize($job['url']), true, IOInterface::DEBUG); } fclose($job['bodyHandle']); if ($response->getStatusCode() >= 300 && $response->getHeader('content-type') === 'application/json') { HttpDownloader::outputWarnings($this->io, $job['origin'], json_decode($response->getBody(), true)); } $result = $this->isAuthenticatedRetryNeeded($job, $response); if ($result['retry']) { $this->restartJob($job, $job['url'], ['storeAuth' => $result['storeAuth'], 'retries' => $job['attributes']['retries'] + 1]); continue; } // handle 3xx redirects, 304 Not Modified is excluded if ($statusCode >= 300 && $statusCode <= 399 && $statusCode !== 304 && $job['attributes']['redirects'] < $this->maxRedirects) { $location = $this->handleRedirect($job, $response); if ($location) { $this->restartJob($job, $location, ['redirects' => $job['attributes']['redirects'] + 1]); continue; } } // fail 4xx and 5xx responses and capture the response if ($statusCode >= 400 && $statusCode <= 599) { if ( (!isset($job['options']['http']['method']) || $job['options']['http']['method'] === 'GET') && in_array($statusCode, [423, 425, 500, 502, 503, 504, 507, 510], true) && $job['attributes']['retries'] < $this->maxRetries ) { $this->io->writeError('Retrying ('.($job['attributes']['retries'] + 1).') ' . Url::sanitize($job['url']) . ' due to status code '. $statusCode, true, IOInterface::DEBUG); $this->restartJobWithDelay($job, $job['url'], ['retries' => $job['attributes']['retries'] + 1]); continue; } throw $this->failResponse($job, $response, $response->getStatusMessage()); } if ($job['attributes']['storeAuth'] !== false) { $this->authHelper->storeAuth($job['origin'], $job['attributes']['storeAuth']); } // resolve promise if (null !== $job['filename']) { rename($job['filename'].'~', $job['filename']); $job['resolve']($response); } else { $job['resolve']($response); } } catch (\Exception $e) { if ($e instanceof TransportException) { if (null !== $headers) { $e->setHeaders($headers); $e->setStatusCode($statusCode); } if (null !== $response) { $e->setResponse($response->getBody()); } $e->setResponseInfo($progress); } $this->rejectJob($job, $e); } } foreach ($this->jobs as $i => $curlHandle) { $curlHandle = $this->jobs[$i]['curlHandle']; $progress = array_diff_key(curl_getinfo($curlHandle), self::$timeInfo); if ($this->jobs[$i]['progress'] !== $progress) { $this->jobs[$i]['progress'] = $progress; if (isset($this->jobs[$i]['options']['max_file_size'])) { // Compare max_file_size with the content-length header this value will be -1 until the header is parsed if ($this->jobs[$i]['options']['max_file_size'] < $progress['download_content_length']) { $this->rejectJob($this->jobs[$i], new MaxFileSizeExceededException('Maximum allowed download size reached. Content-length header indicates ' . $progress['download_content_length'] . ' bytes. Allowed ' . $this->jobs[$i]['options']['max_file_size'] . ' bytes')); } // Compare max_file_size with the download size in bytes if ($this->jobs[$i]['options']['max_file_size'] < $progress['size_download']) { $this->rejectJob($this->jobs[$i], new MaxFileSizeExceededException('Maximum allowed download size reached. Downloaded ' . $progress['size_download'] . ' of allowed ' . $this->jobs[$i]['options']['max_file_size'] . ' bytes')); } } if (isset($progress['primary_ip']) && $progress['primary_ip'] !== $this->jobs[$i]['primaryIp']) { if ( isset($this->jobs[$i]['options']['prevent_ip_access_callable']) && is_callable($this->jobs[$i]['options']['prevent_ip_access_callable']) && $this->jobs[$i]['options']['prevent_ip_access_callable']($progress['primary_ip']) ) { $this->rejectJob($this->jobs[$i], new TransportException(sprintf('IP "%s" is blocked for "%s".', $progress['primary_ip'], $progress['url']))); } $this->jobs[$i]['primaryIp'] = (string) $progress['primary_ip']; } // TODO progress } } } /** * @param Job $job */ private function handleRedirect(array $job, Response $response): string { if ($locationHeader = $response->getHeader('location')) { if (parse_url($locationHeader, PHP_URL_SCHEME)) { // Absolute URL; e.g. https://example.com/composer $targetUrl = $locationHeader; } elseif (parse_url($locationHeader, PHP_URL_HOST)) { // Scheme relative; e.g. //example.com/foo $targetUrl = parse_url($job['url'], PHP_URL_SCHEME).':'.$locationHeader; } elseif ('/' === $locationHeader[0]) { // Absolute path; e.g. /foo $urlHost = parse_url($job['url'], PHP_URL_HOST); // Replace path using hostname as an anchor. $targetUrl = Preg::replace('{^(.+(?://|@)'.preg_quote($urlHost).'(?::\d+)?)(?:[/\?].*)?$}', '\1'.$locationHeader, $job['url']); } else { // Relative path; e.g. foo // This actually differs from PHP which seems to add duplicate slashes. $targetUrl = Preg::replace('{^(.+/)[^/?]*(?:\?.*)?$}', '\1'.$locationHeader, $job['url']); } } if (!empty($targetUrl)) { $this->io->writeError(sprintf('Following redirect (%u) %s', $job['attributes']['redirects'] + 1, Url::sanitize($targetUrl)), true, IOInterface::DEBUG); return $targetUrl; } throw new TransportException('The "'.$job['url'].'" file could not be downloaded, got redirect without Location ('.$response->getStatusMessage().')'); } /** * @param Job $job * @return array{retry: bool, storeAuth: 'prompt'|bool} */ private function isAuthenticatedRetryNeeded(array $job, Response $response): array { if (in_array($response->getStatusCode(), [401, 403]) && $job['attributes']['retryAuthFailure']) { $result = $this->authHelper->promptAuthIfNeeded($job['url'], $job['origin'], $response->getStatusCode(), $response->getStatusMessage(), $response->getHeaders(), $job['attributes']['retries']); if ($result['retry']) { return $result; } } $locationHeader = $response->getHeader('location'); $needsAuthRetry = false; // check for bitbucket login page asking to authenticate if ( $job['origin'] === 'bitbucket.org' && !$this->authHelper->isPublicBitBucketDownload($job['url']) && substr($job['url'], -4) === '.zip' && (!$locationHeader || substr($locationHeader, -4) !== '.zip') && Preg::isMatch('{^text/html\b}i', $response->getHeader('content-type')) ) { $needsAuthRetry = 'Bitbucket requires authentication and it was not provided'; } // check for gitlab 404 when downloading archives if ( $response->getStatusCode() === 404 && in_array($job['origin'], $this->config->get('gitlab-domains'), true) && false !== strpos($job['url'], 'archive.zip') ) { $needsAuthRetry = 'GitLab requires authentication and it was not provided'; } if ($needsAuthRetry) { if ($job['attributes']['retryAuthFailure']) { $result = $this->authHelper->promptAuthIfNeeded($job['url'], $job['origin'], 401, null, [], $job['attributes']['retries']); if ($result['retry']) { return $result; } } throw $this->failResponse($job, $response, $needsAuthRetry); } return ['retry' => false, 'storeAuth' => false]; } /** * @param Job $job * @param non-empty-string $url * * @param array{retryAuthFailure?: bool, redirects?: int<0, max>, storeAuth?: 'prompt'|bool, retries?: int<1, max>, ipResolve?: 4|6} $attributes */ private function restartJob(array $job, string $url, array $attributes = []): void { if (null !== $job['filename']) { @unlink($job['filename'].'~'); } $attributes = array_merge($job['attributes'], $attributes); $origin = Url::getOrigin($this->config, $url); $this->initDownload($job['resolve'], $job['reject'], $origin, $url, $job['options'], $job['filename'], $attributes); } /** * @param Job $job * @param non-empty-string $url * * @param array{retryAuthFailure?: bool, redirects?: int<0, max>, storeAuth?: 'prompt'|bool, retries: int<1, max>, ipResolve?: 4|6} $attributes */ private function restartJobWithDelay(array $job, string $url, array $attributes): void { if ($attributes['retries'] >= 3) { usleep(500000); // half a second delay for 3rd retry and beyond } elseif ($attributes['retries'] >= 2) { usleep(100000); // 100ms delay for 2nd retry } // no sleep for the first retry $this->restartJob($job, $url, $attributes); } /** * @param Job $job */ private function failResponse(array $job, Response $response, string $errorMessage): TransportException { if (null !== $job['filename']) { @unlink($job['filename'].'~'); } $details = ''; if (in_array(strtolower((string) $response->getHeader('content-type')), ['application/json', 'application/json; charset=utf-8'], true)) { $details = ':'.PHP_EOL.substr($response->getBody(), 0, 200).(strlen($response->getBody()) > 200 ? '...' : ''); } return new TransportException('The "'.$job['url'].'" file could not be downloaded ('.$errorMessage.')' . $details, $response->getStatusCode()); } /** * @param Job $job */ private function rejectJob(array $job, \Exception $e): void { if (is_resource($job['headerHandle'])) { fclose($job['headerHandle']); } if (is_resource($job['bodyHandle'])) { fclose($job['bodyHandle']); } if (null !== $job['filename']) { @unlink($job['filename'].'~'); } $job['reject']($e); } private function checkCurlResult(int $code): void { if ($code !== CURLM_OK && $code !== CURLM_CALL_MULTI_PERFORM) { throw new \RuntimeException( isset($this->multiErrors[$code]) ? "cURL error: {$code} ({$this->multiErrors[$code][0]}): cURL message: {$this->multiErrors[$code][1]}" : 'Unexpected cURL error: ' . $code ); } } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Util/Http/CurlResponse.php
src/Composer/Util/Http/CurlResponse.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\Util\Http; /** * @phpstan-type CurlInfo array{url: mixed, content_type: mixed, http_code: mixed, header_size: mixed, request_size: mixed, filetime: mixed, ssl_verify_result: mixed, redirect_count: mixed, total_time: mixed, namelookup_time: mixed, connect_time: mixed, pretransfer_time: mixed, size_upload: mixed, size_download: mixed, speed_download: mixed, speed_upload: mixed, download_content_length: mixed, upload_content_length: mixed, starttransfer_time: mixed, redirect_time: mixed, certinfo: mixed, primary_ip: mixed, primary_port: mixed, local_ip: mixed, local_port: mixed, redirect_url: mixed} */ class CurlResponse extends Response { /** * @see https://www.php.net/curl_getinfo * @var array * @phpstan-var CurlInfo */ private $curlInfo; /** * @phpstan-param CurlInfo $curlInfo */ public function __construct(array $request, ?int $code, array $headers, ?string $body, array $curlInfo) { parent::__construct($request, $code, $headers, $body); $this->curlInfo = $curlInfo; } /** * @phpstan-return CurlInfo */ public function getCurlInfo(): array { return $this->curlInfo; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Config/ConfigSourceInterface.php
src/Composer/Config/ConfigSourceInterface.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\Config; /** * Configuration Source Interface * * @author Jordi Boggiano <j.boggiano@seld.be> * @author Beau Simensen <beau@dflydev.com> */ interface ConfigSourceInterface { /** * Add a repository * * @param string $name Name * @param mixed[]|false $config Configuration * @param bool $append Whether the repo should be appended (true) or prepended (false) */ public function addRepository(string $name, $config, bool $append = true): void; /** * Inserts a repository before/after another repository by name * * @param string $name Name * @param mixed[]|false $config Configuration * @param string $referenceName The referenced repository to search for and insert next to * @param int $offset The offset to use for insert in reference to the looked-up repository */ public function insertRepository(string $name, $config, string $referenceName, int $offset = 0): void; /** * Changes the URL of the referenced repository by name */ public function setRepositoryUrl(string $name, string $url): void; /** * Remove a repository */ public function removeRepository(string $name): void; /** * Add a config setting * * @param string $name Name * @param mixed $value Value */ public function addConfigSetting(string $name, $value): void; /** * Remove a config setting */ public function removeConfigSetting(string $name): void; /** * Add a property * * @param string $name Name * @param string|string[] $value Value */ public function addProperty(string $name, $value): void; /** * Remove a property */ public function removeProperty(string $name): void; /** * Add a package link * * @param string $type Type (require, require-dev, provide, suggest, replace, conflict) * @param string $name Name * @param string $value Value */ public function addLink(string $type, string $name, string $value): void; /** * Remove a package link * * @param string $type Type (require, require-dev, provide, suggest, replace, conflict) * @param string $name Name */ public function removeLink(string $type, string $name): void; /** * Gives a user-friendly name to this source (file path or so) */ public function getName(): string; }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Config/JsonConfigSource.php
src/Composer/Config/JsonConfigSource.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\Config; use Composer\Json\JsonFile; use Composer\Json\JsonManipulator; use Composer\Json\JsonValidationException; use Composer\Pcre\Preg; use Composer\Util\Filesystem; use Composer\Util\Silencer; /** * JSON Configuration Source * * @author Jordi Boggiano <j.boggiano@seld.be> * @author Beau Simensen <beau@dflydev.com> */ class JsonConfigSource implements ConfigSourceInterface { /** * @var JsonFile */ private $file; /** * @var bool */ private $authConfig; /** * Constructor */ public function __construct(JsonFile $file, bool $authConfig = false) { $this->file = $file; $this->authConfig = $authConfig; } /** * @inheritDoc */ public function getName(): string { return $this->file->getPath(); } /** * @inheritDoc */ public function addRepository(string $name, $config, bool $append = true): void { $this->manipulateJson('addRepository', static function (&$config, $repo, $repoConfig) use ($append): void { if (!array_is_list($config['repositories'] ?? [])) { $list = []; foreach ($config['repositories'] as $repositoryIndex => $repository) { if (is_string($repositoryIndex) && is_array($repository)) { // convert to list entry with name if (!isset($repository['name'])) { $repository = ['name' => $repositoryIndex] + $repository; } $list[] = $repository; } elseif (is_string($repositoryIndex)) { // keep boolean entries (e.g. 'packagist.org' => false) $list[] = [$repositoryIndex => $repository]; } else { $list[] = $repository; } } $config['repositories'] = $list; } if ($repoConfig === false) { if (isset($config['repositories'])) { foreach ($config['repositories'] as &$repository) { if (($repository['name'] ?? null) === $repo) { $repository = [$repo => $repoConfig]; return; } if ($repository === [$repo => false]) { return; } } unset($repository); } else { $config['repositories'] = []; } $config['repositories'][] = [$repo => $repoConfig]; return; } if (is_array($repoConfig) && $repo !== '' && !isset($repoConfig['name'])) { $repoConfig = ['name' => $repo] + $repoConfig; } // ensure uniqueness by removing any existing entries which use the same name $config['repositories'] = array_values(array_filter($config['repositories'] ?? [], static function ($val) use ($repo) { return !isset($val['name']) || $val['name'] !== $repo || $val !== [$repo => false]; })); if ($append) { $config['repositories'][] = $repoConfig; } else { array_unshift($config['repositories'], $repoConfig); } }, $name, $config, $append); } /** * @inheritDoc */ public function insertRepository(string $name, $config, string $referenceName, int $offset = 0): void { $this->manipulateJson('insertRepository', static function (&$config, string $name, $repoConfig, string $referenceName, int $offset): void { if (!array_is_list($config['repositories'] ?? [])) { $list = []; foreach ($config['repositories'] as $repositoryIndex => $repository) { if (is_string($repositoryIndex) && is_array($repository)) { // convert to list entry with name if (!isset($repository['name'])) { $repository = ['name' => $repositoryIndex] + $repository; } $list[] = $repository; } elseif (is_string($repositoryIndex)) { // keep boolean entries (e.g. 'packagist.org' => false) $list[] = [$repositoryIndex => $repository]; } else { $list[] = $repository; } } $config['repositories'] = $list; } // ensure uniqueness by removing any existing entries which use the same name $config['repositories'] = array_values(array_filter($config['repositories'] ?? [], static function ($val) use ($name) { return !isset($val['name']) || $val['name'] !== $name || $val !== [$name => false]; })); $indexToInsert = null; foreach ($config['repositories'] as $repositoryIndex => $repository) { if (($repository['name'] ?? null) === $referenceName) { $indexToInsert = $repositoryIndex; break; } if ([$referenceName => false] === $repository) { $indexToInsert = $repositoryIndex; break; } } if ($indexToInsert === null) { throw new \RuntimeException(sprintf('The referenced repository "%s" does not exist.', $referenceName)); } if (is_array($repoConfig) && $name !== '' && !isset($repoConfig['name'])) { $repoConfig = ['name' => $name] + $repoConfig; } array_splice($config['repositories'], $indexToInsert + $offset, 0, [$repoConfig]); }, $name, $config, $referenceName, $offset); } /** * @inheritDoc */ public function setRepositoryUrl(string $name, string $url): void { $this->manipulateJson('setRepositoryUrl', static function (&$config, $name, $url): void { foreach ($config['repositories'] ?? [] as $index => $repository) { if ($name === $index) { $config['repositories'][$index]['url'] = $url; return; } if ($name === ($repository['name'] ?? null)) { $config['repositories'][$index]['url'] = $url; return; } } }, $name, $url); } /** * @inheritDoc */ public function removeRepository(string $name): void { $this->manipulateJson('removeRepository', static function (&$config, $repo): void { if (isset($config['repositories'][$repo])) { unset($config['repositories'][$repo]); } else { $config['repositories'] = array_values(array_filter($config['repositories'] ?? [], static function ($val) use ($repo) { return !isset($val['name']) || $val['name'] !== $repo || $val !== [$repo => false]; })); } if ([] === $config['repositories']) { unset($config['repositories']); } }, $name); } /** * @inheritDoc */ public function addConfigSetting(string $name, $value): void { $authConfig = $this->authConfig; $this->manipulateJson('addConfigSetting', static function (&$config, $key, $val) use ($authConfig): void { if (Preg::isMatch('{^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|bearer|http-basic|custom-headers|forgejo-token|platform)\.}', $key)) { [$key, $host] = explode('.', $key, 2); if ($authConfig) { $config[$key][$host] = $val; } else { $config['config'][$key][$host] = $val; } } else { $config['config'][$key] = $val; } }, $name, $value); } /** * @inheritDoc */ public function removeConfigSetting(string $name): void { $authConfig = $this->authConfig; $this->manipulateJson('removeConfigSetting', static function (&$config, $key) use ($authConfig): void { if (Preg::isMatch('{^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|bearer|http-basic|custom-headers|forgejo-token|platform)\.}', $key)) { [$key, $host] = explode('.', $key, 2); if ($authConfig) { unset($config[$key][$host]); } else { unset($config['config'][$key][$host]); } } else { unset($config['config'][$key]); } }, $name); } /** * @inheritDoc */ public function addProperty(string $name, $value): void { $this->manipulateJson('addProperty', static function (&$config, $key, $val): void { if (strpos($key, 'extra.') === 0 || strpos($key, 'scripts.') === 0) { $bits = explode('.', $key); $last = array_pop($bits); $arr = &$config[reset($bits)]; foreach ($bits as $bit) { if (!isset($arr[$bit])) { $arr[$bit] = []; } $arr = &$arr[$bit]; } $arr[$last] = $val; } else { $config[$key] = $val; } }, $name, $value); } /** * @inheritDoc */ public function removeProperty(string $name): void { $this->manipulateJson('removeProperty', static function (&$config, $key): void { if (strpos($key, 'extra.') === 0 || strpos($key, 'scripts.') === 0 || stripos($key, 'autoload.') === 0 || stripos($key, 'autoload-dev.') === 0) { $bits = explode('.', $key); $last = array_pop($bits); $arr = &$config[reset($bits)]; foreach ($bits as $bit) { if (!isset($arr[$bit])) { return; } $arr = &$arr[$bit]; } unset($arr[$last]); } else { unset($config[$key]); } }, $name); } /** * @inheritDoc */ public function addLink(string $type, string $name, string $value): void { $this->manipulateJson('addLink', static function (&$config, $type, $name, $value): void { $config[$type][$name] = $value; }, $type, $name, $value); } /** * @inheritDoc */ public function removeLink(string $type, string $name): void { $this->manipulateJson('removeSubNode', static function (&$config, $type, $name): void { unset($config[$type][$name]); }, $type, $name); $this->manipulateJson('removeMainKeyIfEmpty', static function (&$config, $type): void { if (0 === count($config[$type])) { unset($config[$type]); } }, $type); } /** * @param mixed ...$args */ private function manipulateJson(string $method, callable $fallback, ...$args): void { if ($this->file->exists()) { if (!is_writable($this->file->getPath())) { throw new \RuntimeException(sprintf('The file "%s" is not writable.', $this->file->getPath())); } if (!Filesystem::isReadable($this->file->getPath())) { throw new \RuntimeException(sprintf('The file "%s" is not readable.', $this->file->getPath())); } $contents = file_get_contents($this->file->getPath()); } elseif ($this->authConfig) { $contents = "{\n}\n"; } else { $contents = "{\n \"config\": {\n }\n}\n"; } $manipulator = new JsonManipulator($contents); $newFile = !$this->file->exists(); // override manipulator method for auth config files if ($this->authConfig && $method === 'addConfigSetting') { $method = 'addSubNode'; [$mainNode, $name] = explode('.', $args[0], 2); $args = [$mainNode, $name, $args[1]]; } elseif ($this->authConfig && $method === 'removeConfigSetting') { $method = 'removeSubNode'; [$mainNode, $name] = explode('.', $args[0], 2); $args = [$mainNode, $name]; } // try to update cleanly if (call_user_func_array([$manipulator, $method], $args)) { file_put_contents($this->file->getPath(), $manipulator->getContents()); } else { // on failed clean update, call the fallback and rewrite the whole file $config = $this->file->read(); $this->arrayUnshiftRef($args, $config); $fallback(...$args); // avoid ending up with arrays for keys that should be objects foreach (['require', 'require-dev', 'conflict', 'provide', 'replace', 'suggest', 'config', 'autoload', 'autoload-dev', 'scripts', 'scripts-descriptions', 'scripts-aliases', 'support'] as $prop) { if (isset($config[$prop]) && $config[$prop] === []) { $config[$prop] = new \stdClass; } } foreach (['psr-0', 'psr-4'] as $prop) { if (isset($config['autoload'][$prop]) && $config['autoload'][$prop] === []) { $config['autoload'][$prop] = new \stdClass; } if (isset($config['autoload-dev'][$prop]) && $config['autoload-dev'][$prop] === []) { $config['autoload-dev'][$prop] = new \stdClass; } } foreach (['platform', 'http-basic', 'bearer', 'gitlab-token', 'gitlab-oauth', 'github-oauth', 'custom-headers', 'forgejo-token', 'preferred-install'] as $prop) { if (isset($config['config'][$prop]) && $config['config'][$prop] === []) { $config['config'][$prop] = new \stdClass; } } $this->file->write($config); } try { $this->file->validateSchema(JsonFile::LAX_SCHEMA); } catch (JsonValidationException $e) { // restore contents to the original state file_put_contents($this->file->getPath(), $contents); throw new \RuntimeException('Failed to update composer.json with a valid format, reverting to the original content. Please report an issue to us with details (command you run and a copy of your composer.json). '.PHP_EOL.implode(PHP_EOL, $e->getErrors()), 0, $e); } if ($newFile) { Silencer::call('chmod', $this->file->getPath(), 0600); } } /** * Prepend a reference to an element to the beginning of an array. * * @param mixed[] $array * @param mixed $value */ private function arrayUnshiftRef(array &$array, &$value): int { $return = array_unshift($array, ''); $array[0] = &$value; return $return; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Exception/NoSslException.php
src/Composer/Exception/NoSslException.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\Exception; /** * Specific exception for Composer\Util\HttpDownloader creation. * * @author Jordi Boggiano <j.boggiano@seld.be> */ class NoSslException extends \RuntimeException { }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Exception/IrrecoverableDownloadException.php
src/Composer/Exception/IrrecoverableDownloadException.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\Exception; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class IrrecoverableDownloadException extends \RuntimeException { }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Link.php
src/Composer/Package/Link.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; use Composer\Semver\Constraint\ConstraintInterface; /** * Represents a link between two packages, represented by their names * * @author Nils Adermann <naderman@naderman.de> */ class Link { public const TYPE_REQUIRE = 'requires'; public const TYPE_DEV_REQUIRE = 'devRequires'; public const TYPE_PROVIDE = 'provides'; public const TYPE_CONFLICT = 'conflicts'; public const TYPE_REPLACE = 'replaces'; /** * Special type * @internal */ public const TYPE_DOES_NOT_REQUIRE = 'does not require'; private const TYPE_UNKNOWN = 'relates to'; /** * Will be converted into a constant once the min PHP version allows this * * @internal * @var string[] * @phpstan-var array<self::TYPE_REQUIRE|self::TYPE_DEV_REQUIRE|self::TYPE_PROVIDE|self::TYPE_CONFLICT|self::TYPE_REPLACE> */ public static $TYPES = [ self::TYPE_REQUIRE, self::TYPE_DEV_REQUIRE, self::TYPE_PROVIDE, self::TYPE_CONFLICT, self::TYPE_REPLACE, ]; /** * @var string */ protected $source; /** * @var string */ protected $target; /** * @var ConstraintInterface */ protected $constraint; /** * @var string * @phpstan-var string $description */ protected $description; /** * @var ?string */ protected $prettyConstraint; /** * Creates a new package link. * * @param ConstraintInterface $constraint Constraint applying to the target of this link * @param self::TYPE_* $description Used to create a descriptive string representation */ public function __construct( string $source, string $target, ConstraintInterface $constraint, $description = self::TYPE_UNKNOWN, ?string $prettyConstraint = null ) { $this->source = strtolower($source); $this->target = strtolower($target); $this->constraint = $constraint; $this->description = self::TYPE_DEV_REQUIRE === $description ? 'requires (for development)' : $description; $this->prettyConstraint = $prettyConstraint; } public function getDescription(): string { return $this->description; } public function getSource(): string { return $this->source; } public function getTarget(): string { return $this->target; } public function getConstraint(): ConstraintInterface { return $this->constraint; } /** * @throws \UnexpectedValueException If no pretty constraint was provided */ public function getPrettyConstraint(): string { if (null === $this->prettyConstraint) { throw new \UnexpectedValueException(sprintf('Link %s has been misconfigured and had no prettyConstraint given.', $this)); } return $this->prettyConstraint; } public function __toString(): string { return $this->source.' '.$this->description.' '.$this->target.' ('.$this->constraint.')'; } public function getPrettyString(PackageInterface $sourcePackage): string { return $sourcePackage->getPrettyString().' '.$this->description.' '.$this->target.' '.$this->constraint->getPrettyString(); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/CompleteAliasPackage.php
src/Composer/Package/CompleteAliasPackage.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; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class CompleteAliasPackage extends AliasPackage implements CompletePackageInterface { /** @var CompletePackage */ protected $aliasOf; /** * All descendants' constructors should call this parent constructor * * @param CompletePackage $aliasOf The package this package is an alias of * @param string $version The version the alias must report * @param string $prettyVersion The alias's non-normalized version */ public function __construct(CompletePackage $aliasOf, string $version, string $prettyVersion) { parent::__construct($aliasOf, $version, $prettyVersion); } /** * @return CompletePackage */ public function getAliasOf() { return $this->aliasOf; } public function getScripts(): array { return $this->aliasOf->getScripts(); } public function setScripts(array $scripts): void { $this->aliasOf->setScripts($scripts); } public function getRepositories(): array { return $this->aliasOf->getRepositories(); } public function setRepositories(array $repositories): void { $this->aliasOf->setRepositories($repositories); } public function getLicense(): array { return $this->aliasOf->getLicense(); } public function setLicense(array $license): void { $this->aliasOf->setLicense($license); } public function getKeywords(): array { return $this->aliasOf->getKeywords(); } public function setKeywords(array $keywords): void { $this->aliasOf->setKeywords($keywords); } public function getDescription(): ?string { return $this->aliasOf->getDescription(); } public function setDescription(?string $description): void { $this->aliasOf->setDescription($description); } public function getHomepage(): ?string { return $this->aliasOf->getHomepage(); } public function setHomepage(?string $homepage): void { $this->aliasOf->setHomepage($homepage); } public function getAuthors(): array { return $this->aliasOf->getAuthors(); } public function setAuthors(array $authors): void { $this->aliasOf->setAuthors($authors); } public function getSupport(): array { return $this->aliasOf->getSupport(); } public function setSupport(array $support): void { $this->aliasOf->setSupport($support); } public function getFunding(): array { return $this->aliasOf->getFunding(); } public function setFunding(array $funding): void { $this->aliasOf->setFunding($funding); } public function isAbandoned(): bool { return $this->aliasOf->isAbandoned(); } public function getReplacementPackage(): ?string { return $this->aliasOf->getReplacementPackage(); } public function setAbandoned($abandoned): void { $this->aliasOf->setAbandoned($abandoned); } public function getArchiveName(): ?string { return $this->aliasOf->getArchiveName(); } public function setArchiveName(?string $name): void { $this->aliasOf->setArchiveName($name); } public function getArchiveExcludes(): array { return $this->aliasOf->getArchiveExcludes(); } public function setArchiveExcludes(array $excludes): void { $this->aliasOf->setArchiveExcludes($excludes); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/RootPackageInterface.php
src/Composer/Package/RootPackageInterface.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; /** * Defines additional fields that are only needed for the root package * * PackageInterface & derivatives are considered internal, you may use them in type hints but extending/implementing them is not recommended and not supported. Things may change without notice. * * @author Jordi Boggiano <j.boggiano@seld.be> * * @phpstan-import-type AutoloadRules from PackageInterface * @phpstan-import-type DevAutoloadRules from PackageInterface */ interface RootPackageInterface extends CompletePackageInterface { /** * Returns a set of package names and their aliases * * @return list<array{package: string, version: string, alias: string, alias_normalized: string}> */ public function getAliases(): array; /** * Returns the minimum stability of the package * * @return key-of<BasePackage::STABILITIES> */ public function getMinimumStability(): string; /** * Returns the stability flags to apply to dependencies * * array('foo/bar' => 'dev') * * @return array<string, BasePackage::STABILITY_*> */ public function getStabilityFlags(): array; /** * Returns a set of package names and source references that must be enforced on them * * array('foo/bar' => 'abcd1234') * * @return array<string, string> */ public function getReferences(): array; /** * Returns true if the root package prefers picking stable packages over unstable ones */ public function getPreferStable(): bool; /** * Returns the root package's configuration * * @return mixed[] */ public function getConfig(): array; /** * Set the required packages * * @param Link[] $requires A set of package links */ public function setRequires(array $requires): void; /** * Set the recommended packages * * @param Link[] $devRequires A set of package links */ public function setDevRequires(array $devRequires): void; /** * Set the conflicting packages * * @param Link[] $conflicts A set of package links */ public function setConflicts(array $conflicts): void; /** * Set the provided virtual packages * * @param Link[] $provides A set of package links */ public function setProvides(array $provides): void; /** * Set the packages this one replaces * * @param Link[] $replaces A set of package links */ public function setReplaces(array $replaces): void; /** * Set the autoload mapping * * @param array $autoload Mapping of autoloading rules * @phpstan-param AutoloadRules $autoload */ public function setAutoload(array $autoload): void; /** * Set the dev autoload mapping * * @param array $devAutoload Mapping of dev autoloading rules * @phpstan-param DevAutoloadRules $devAutoload */ public function setDevAutoload(array $devAutoload): void; /** * Set the stabilityFlags * * @phpstan-param array<string, BasePackage::STABILITY_*> $stabilityFlags */ public function setStabilityFlags(array $stabilityFlags): void; /** * Set the minimumStability * * @phpstan-param key-of<BasePackage::STABILITIES> $minimumStability */ public function setMinimumStability(string $minimumStability): void; /** * Set the preferStable */ public function setPreferStable(bool $preferStable): void; /** * Set the config * * @param mixed[] $config */ public function setConfig(array $config): void; /** * Set the references * * @param array<string, string> $references */ public function setReferences(array $references): void; /** * Set the aliases * * @param list<array{package: string, version: string, alias: string, alias_normalized: string}> $aliases */ public function setAliases(array $aliases): void; /** * Set the suggested packages * * @param array<string, string> $suggests A set of package names/comments */ public function setSuggests(array $suggests): void; /** * @param mixed[] $extra */ public function setExtra(array $extra): void; }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Locker.php
src/Composer/Package/Locker.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; use Composer\Json\JsonFile; use Composer\Installer\InstallationManager; use Composer\Pcre\Preg; use Composer\Repository\InstalledRepository; use Composer\Repository\LockArrayRepository; use Composer\Repository\PlatformRepository; use Composer\Repository\RootPackageRepository; use Composer\Util\ProcessExecutor; use Composer\Package\Dumper\ArrayDumper; use Composer\Package\Loader\ArrayLoader; use Composer\Package\Version\VersionParser; use Composer\Plugin\PluginInterface; use Composer\Util\Git as GitUtil; use Composer\IO\IOInterface; use Seld\JsonLint\ParsingException; /** * Reads/writes project lockfile (composer.lock). * * @author Konstantin Kudryashiv <ever.zet@gmail.com> * @author Jordi Boggiano <j.boggiano@seld.be> */ class Locker { /** @var JsonFile */ private $lockFile; /** @var InstallationManager */ private $installationManager; /** @var string */ private $hash; /** @var string */ private $contentHash; /** @var ArrayLoader */ private $loader; /** @var ArrayDumper */ private $dumper; /** @var ProcessExecutor */ private $process; /** @var mixed[]|null */ private $lockDataCache = null; /** @var bool */ private $virtualFileWritten = false; /** * Initializes packages locker. * * @param JsonFile $lockFile lockfile loader * @param InstallationManager $installationManager installation manager instance * @param string $composerFileContents The contents of the composer file */ public function __construct(IOInterface $io, JsonFile $lockFile, InstallationManager $installationManager, string $composerFileContents, ?ProcessExecutor $process = null) { $this->lockFile = $lockFile; $this->installationManager = $installationManager; $this->hash = hash('md5', $composerFileContents); $this->contentHash = self::getContentHash($composerFileContents); $this->loader = new ArrayLoader(null, true); $this->dumper = new ArrayDumper(); $this->process = $process ?? new ProcessExecutor($io); } /** * @internal */ public function getJsonFile(): JsonFile { return $this->lockFile; } /** * Returns the md5 hash of the sorted content of the composer file. * * @param string $composerFileContents The contents of the composer file. */ public static function getContentHash(string $composerFileContents): string { $content = JsonFile::parseJson($composerFileContents, 'composer.json'); $relevantKeys = [ 'name', 'version', 'require', 'require-dev', 'conflict', 'replace', 'provide', 'minimum-stability', 'prefer-stable', 'repositories', 'extra', ]; $relevantContent = []; foreach (array_intersect($relevantKeys, array_keys($content)) as $key) { $relevantContent[$key] = $content[$key]; } if (isset($content['config']['platform'])) { $relevantContent['config']['platform'] = $content['config']['platform']; } ksort($relevantContent); return hash('md5', JsonFile::encode($relevantContent, 0)); } /** * Checks whether locker has been locked (lockfile found). */ public function isLocked(): bool { if (!$this->virtualFileWritten && !$this->lockFile->exists()) { return false; } $data = $this->getLockData(); return isset($data['packages']); } /** * Checks whether the lock file is still up to date with the current hash */ public function isFresh(): bool { $lock = $this->lockFile->read(); if (!empty($lock['content-hash'])) { // There is a content hash key, use that instead of the file hash return $this->contentHash === $lock['content-hash']; } // BC support for old lock files without content-hash if (!empty($lock['hash'])) { return $this->hash === $lock['hash']; } // should not be reached unless the lock file is corrupted, so assume it's out of date return false; } /** * Searches and returns an array of locked packages, retrieved from registered repositories. * * @param bool $withDevReqs true to retrieve the locked dev packages * @throws \RuntimeException */ public function getLockedRepository(bool $withDevReqs = false): LockArrayRepository { $lockData = $this->getLockData(); $packages = new LockArrayRepository(); $lockedPackages = $lockData['packages']; if ($withDevReqs) { if (isset($lockData['packages-dev'])) { $lockedPackages = array_merge($lockedPackages, $lockData['packages-dev']); } else { throw new \RuntimeException('The lock file does not contain require-dev information, run install with the --no-dev option or delete it and run composer update to generate a new lock file.'); } } if (empty($lockedPackages)) { return $packages; } if (isset($lockedPackages[0]['name'])) { $packageByName = []; foreach ($lockedPackages as $info) { $package = $this->loader->load($info); $packages->addPackage($package); $packageByName[$package->getName()] = $package; if ($package instanceof AliasPackage) { $packageByName[$package->getAliasOf()->getName()] = $package->getAliasOf(); } } if (isset($lockData['aliases'])) { foreach ($lockData['aliases'] as $alias) { if (isset($packageByName[$alias['package']])) { $aliasPkg = new CompleteAliasPackage($packageByName[$alias['package']], $alias['alias_normalized'], $alias['alias']); $aliasPkg->setRootPackageAlias(true); $packages->addPackage($aliasPkg); } } } return $packages; } throw new \RuntimeException('Your composer.lock is invalid. Run "composer update" to generate a new one.'); } /** * @return string[] Names of dependencies installed through require-dev */ public function getDevPackageNames(): array { $names = []; $lockData = $this->getLockData(); if (isset($lockData['packages-dev'])) { foreach ($lockData['packages-dev'] as $package) { $names[] = strtolower($package['name']); } } return $names; } /** * Returns the platform requirements stored in the lock file * * @param bool $withDevReqs if true, the platform requirements from the require-dev block are also returned * @return Link[] */ public function getPlatformRequirements(bool $withDevReqs = false): array { $lockData = $this->getLockData(); $requirements = []; if (!empty($lockData['platform'])) { $requirements = $this->loader->parseLinks( '__root__', '1.0.0', Link::TYPE_REQUIRE, $lockData['platform'] ?? [] ); } if ($withDevReqs && !empty($lockData['platform-dev'])) { $devRequirements = $this->loader->parseLinks( '__root__', '1.0.0', Link::TYPE_REQUIRE, $lockData['platform-dev'] ?? [] ); $requirements = array_merge($requirements, $devRequirements); } return $requirements; } /** * @return key-of<BasePackage::STABILITIES> */ public function getMinimumStability(): string { $lockData = $this->getLockData(); return $lockData['minimum-stability'] ?? 'stable'; } /** * @return array<string, string> */ public function getStabilityFlags(): array { $lockData = $this->getLockData(); return $lockData['stability-flags'] ?? []; } public function getPreferStable(): ?bool { $lockData = $this->getLockData(); // return null if not set to allow caller logic to choose the // right behavior since old lock files have no prefer-stable return $lockData['prefer-stable'] ?? null; } public function getPreferLowest(): ?bool { $lockData = $this->getLockData(); // return null if not set to allow caller logic to choose the // right behavior since old lock files have no prefer-lowest return $lockData['prefer-lowest'] ?? null; } /** * @return array<string, string> */ public function getPlatformOverrides(): array { $lockData = $this->getLockData(); return $lockData['platform-overrides'] ?? []; } /** * @return string[][] * * @phpstan-return list<array{package: string, version: string, alias: string, alias_normalized: string}> */ public function getAliases(): array { $lockData = $this->getLockData(); return $lockData['aliases'] ?? []; } /** * @return string */ public function getPluginApi() { $lockData = $this->getLockData(); return $lockData['plugin-api-version'] ?? '1.1.0'; } /** * @return array<string, mixed> */ public function getLockData(): array { if (null !== $this->lockDataCache) { return $this->lockDataCache; } if (!$this->lockFile->exists()) { throw new \LogicException('No lockfile found. Unable to read locked packages'); } return $this->lockDataCache = $this->lockFile->read(); } /** * Locks provided data into lockfile. * * @param PackageInterface[] $packages array of packages * @param PackageInterface[]|null $devPackages array of dev packages or null if installed without --dev * @param array<string, string> $platformReqs array of package name => constraint for required platform packages * @param array<string, string> $platformDevReqs array of package name => constraint for dev-required platform packages * @param string[][] $aliases array of aliases * @param array<string, int> $stabilityFlags * @param array<string, string|false> $platformOverrides * @param bool $write Whether to actually write data to disk, useful in tests and for --dry-run * * @phpstan-param list<array{package: string, version: string, alias: string, alias_normalized: string}> $aliases */ public function setLockData(array $packages, ?array $devPackages, array $platformReqs, array $platformDevReqs, array $aliases, string $minimumStability, array $stabilityFlags, bool $preferStable, bool $preferLowest, array $platformOverrides, bool $write = true): bool { // keep old default branch names normalized to DEFAULT_BRANCH_ALIAS for BC as that is how Composer 1 outputs the lock file // when loading the lock file the version is anyway ignored in Composer 2, so it has no adverse effect $aliases = array_map(static function ($alias): array { if (in_array($alias['version'], ['dev-master', 'dev-trunk', 'dev-default'], true)) { $alias['version'] = VersionParser::DEFAULT_BRANCH_ALIAS; } return $alias; }, $aliases); $lock = [ '_readme' => ['This file locks the dependencies of your project to a known state', 'Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies', 'This file is @gener'.'ated automatically', ], 'content-hash' => $this->contentHash, 'packages' => $this->lockPackages($packages), 'packages-dev' => null, 'aliases' => $aliases, 'minimum-stability' => $minimumStability, 'stability-flags' => $stabilityFlags, 'prefer-stable' => $preferStable, 'prefer-lowest' => $preferLowest, ]; if (null !== $devPackages) { $lock['packages-dev'] = $this->lockPackages($devPackages); } $lock['platform'] = $platformReqs; $lock['platform-dev'] = $platformDevReqs; if (\count($platformOverrides) > 0) { $lock['platform-overrides'] = $platformOverrides; } $lock['plugin-api-version'] = PluginInterface::PLUGIN_API_VERSION; $lock = $this->fixupJsonDataType($lock); try { $isLocked = $this->isLocked(); } catch (ParsingException $e) { $isLocked = false; } if (!$isLocked || $lock !== $this->getLockData()) { if ($write) { $this->lockFile->write($lock); $this->lockDataCache = null; $this->virtualFileWritten = false; } else { $this->virtualFileWritten = true; $this->lockDataCache = JsonFile::parseJson(JsonFile::encode($lock)); } return true; } return false; } /** * Updates the lock file's hash in-place from a given composer.json's JsonFile * * This does not reload or require any packages, and retains the filemtime of the lock file. * * Use this only to update the lock file hash after updating a composer.json in ways that are guaranteed NOT to impact the dependency resolution. * * This is a risky method, use carefully. * * @param (callable(array<string, mixed>): array<string, mixed>)|null $dataProcessor Receives the lock data and can process it before it gets written to disk */ public function updateHash(JsonFile $composerJson, ?callable $dataProcessor = null): void { $contents = file_get_contents($composerJson->getPath()); if (false === $contents) { throw new \RuntimeException('Unable to read '.$composerJson->getPath().' contents to update the lock file hash.'); } $lockMtime = filemtime($this->lockFile->getPath()); $lockData = $this->lockFile->read(); $lockData['content-hash'] = Locker::getContentHash($contents); if ($dataProcessor !== null) { $lockData = $dataProcessor($lockData); } $this->lockFile->write($this->fixupJsonDataType($lockData)); $this->lockDataCache = null; $this->virtualFileWritten = false; if (is_int($lockMtime)) { @touch($this->lockFile->getPath(), $lockMtime); } } /** * Ensures correct data types and ordering for the JSON lock format * * @param array<mixed> $lockData * @return array<mixed> */ private function fixupJsonDataType(array $lockData): array { foreach (['stability-flags', 'platform', 'platform-dev'] as $key) { if (isset($lockData[$key]) && is_array($lockData[$key]) && \count($lockData[$key]) === 0) { $lockData[$key] = new \stdClass(); } } if (is_array($lockData['stability-flags'])) { ksort($lockData['stability-flags']); } return $lockData; } /** * @param PackageInterface[] $packages * * @return mixed[][] * * @phpstan-return list<array<string, mixed>> */ private function lockPackages(array $packages): array { $locked = []; foreach ($packages as $package) { if ($package instanceof AliasPackage) { continue; } $name = $package->getPrettyName(); $version = $package->getPrettyVersion(); if (!$name || !$version) { throw new \LogicException(sprintf( 'Package "%s" has no version or name and can not be locked', $package )); } $spec = $this->dumper->dump($package); unset($spec['version_normalized']); // always move time to the end of the package definition $time = $spec['time'] ?? null; unset($spec['time']); if ($package->isDev() && $package->getInstallationSource() === 'source') { // use the exact commit time of the current reference if it's a dev package $time = $this->getPackageTime($package) ?: $time; } if (null !== $time) { $spec['time'] = $time; } unset($spec['installation-source']); $locked[] = $spec; } usort($locked, static function ($a, $b) { $comparison = strcmp($a['name'], $b['name']); if (0 !== $comparison) { return $comparison; } // If it is the same package, compare the versions to make the order deterministic return strcmp($a['version'], $b['version']); }); return $locked; } /** * Returns the packages's datetime for its source reference. * * @param PackageInterface $package The package to scan. * @return string|null The formatted datetime or null if none was found. */ private function getPackageTime(PackageInterface $package): ?string { if (!function_exists('proc_open')) { return null; } $path = $this->installationManager->getInstallPath($package); if ($path === null) { return null; } $path = realpath($path); $sourceType = $package->getSourceType(); $datetime = null; if ($path && in_array($sourceType, ['git', 'hg'])) { $sourceRef = $package->getSourceReference() ?: $package->getDistReference(); switch ($sourceType) { case 'git': GitUtil::cleanEnv($this->process); $command = GitUtil::buildRevListCommand($this->process, array_merge(['-n1', '--format=%ct', (string) $sourceRef], GitUtil::getNoShowSignatureFlags($this->process))); if (0 === $this->process->execute($command, $output, $path)) { $output = trim(GitUtil::parseRevListOutput($output, $this->process)); if (Preg::isMatch('{^\s*\d+\s*$}', $output)) { $datetime = new \DateTime('@'.trim($output), new \DateTimeZone('UTC')); } } break; case 'hg': if (0 === $this->process->execute(['hg', 'log', '--template', '{date|hgdate}', '-r', (string) $sourceRef], $output, $path) && Preg::isMatch('{^\s*(\d+)\s*}', $output, $match)) { $datetime = new \DateTime('@'.$match[1], new \DateTimeZone('UTC')); } break; } } return $datetime ? $datetime->format(DATE_RFC3339) : null; } /** * @return array<string> */ public function getMissingRequirementInfo(RootPackageInterface $package, bool $includeDev): array { $missingRequirementInfo = []; $missingRequirements = false; $sets = [['repo' => $this->getLockedRepository(false), 'method' => 'getRequires', 'description' => 'Required']]; if ($includeDev === true) { $sets[] = ['repo' => $this->getLockedRepository(true), 'method' => 'getDevRequires', 'description' => 'Required (in require-dev)']; } $rootRepo = new RootPackageRepository(clone $package); foreach ($sets as $set) { $installedRepo = new InstalledRepository([$set['repo'], $rootRepo]); foreach (call_user_func([$package, $set['method']]) as $link) { if (PlatformRepository::isPlatformPackage($link->getTarget())) { continue; } if ($link->getPrettyConstraint() === 'self.version') { continue; } if ($installedRepo->findPackagesWithReplacersAndProviders($link->getTarget(), $link->getConstraint()) === []) { $results = $installedRepo->findPackagesWithReplacersAndProviders($link->getTarget()); if ($results !== []) { $provider = reset($results); $description = $provider->getPrettyVersion(); if ($provider->getName() !== $link->getTarget()) { foreach (['getReplaces' => 'replaced as %s by %s', 'getProvides' => 'provided as %s by %s'] as $method => $text) { foreach (call_user_func([$provider, $method]) as $providerLink) { if ($providerLink->getTarget() === $link->getTarget()) { $description = sprintf($text, $providerLink->getPrettyConstraint(), $provider->getPrettyName().' '.$provider->getPrettyVersion()); break 2; } } } } $missingRequirementInfo[] = '- ' . $set['description'].' package "' . $link->getTarget() . '" is in the lock file as "'.$description.'" but that does not satisfy your constraint "'.$link->getPrettyConstraint().'".'; } else { $missingRequirementInfo[] = '- ' . $set['description'].' package "' . $link->getTarget() . '" is not present in the lock file.'; } $missingRequirements = true; } } } if ($missingRequirements) { $missingRequirementInfo[] = 'This usually happens when composer files are incorrectly merged or the composer.json file is manually edited.'; $missingRequirementInfo[] = 'Read more about correctly resolving merge conflicts https://getcomposer.org/doc/articles/resolving-merge-conflicts.md'; $missingRequirementInfo[] = 'and prefer using the "require" command over editing the composer.json file directly https://getcomposer.org/doc/03-cli.md#require-r'; } return $missingRequirementInfo; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/CompletePackageInterface.php
src/Composer/Package/CompletePackageInterface.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; /** * Defines package metadata that is not necessarily needed for solving and installing packages * * PackageInterface & derivatives are considered internal, you may use them in type hints but extending/implementing them is not recommended and not supported. Things may change without notice. * * @author Nils Adermann <naderman@naderman.de> */ interface CompletePackageInterface extends PackageInterface { /** * Returns the scripts of this package * * @return array<string, string[]> Map of script name to array of handlers */ public function getScripts(): array; /** * @param array<string, string[]> $scripts */ public function setScripts(array $scripts): void; /** * Returns an array of repositories * * @return mixed[] Repositories */ public function getRepositories(): array; /** * Set the repositories * * @param mixed[] $repositories */ public function setRepositories(array $repositories): void; /** * Returns the package license, e.g. MIT, BSD, GPL * * @return string[] The package licenses */ public function getLicense(): array; /** * Set the license * * @param string[] $license */ public function setLicense(array $license): void; /** * Returns an array of keywords relating to the package * * @return string[] */ public function getKeywords(): array; /** * Set the keywords * * @param string[] $keywords */ public function setKeywords(array $keywords): void; /** * Returns the package description */ public function getDescription(): ?string; /** * Set the description */ public function setDescription(string $description): void; /** * Returns the package homepage */ public function getHomepage(): ?string; /** * Set the homepage */ public function setHomepage(string $homepage): void; /** * Returns an array of authors of the package * * Each item can contain name/homepage/email keys * * @return array<array{name?: string, homepage?: string, email?: string, role?: string}> */ public function getAuthors(): array; /** * Set the authors * * @param array<array{name?: string, homepage?: string, email?: string, role?: string}> $authors */ public function setAuthors(array $authors): void; /** * Returns the support information * * @return array{issues?: string, forum?: string, wiki?: string, source?: string, email?: string, irc?: string, docs?: string, rss?: string, chat?: string, security?: string} */ public function getSupport(): array; /** * Set the support information * * @param array{issues?: string, forum?: string, wiki?: string, source?: string, email?: string, irc?: string, docs?: string, rss?: string, chat?: string, security?: string} $support */ public function setSupport(array $support): void; /** * Returns an array of funding options for the package * * Each item will contain type and url keys * * @return array<array{type?: string, url?: string}> */ public function getFunding(): array; /** * Set the funding * * @param array<array{type?: string, url?: string}> $funding */ public function setFunding(array $funding): void; /** * Returns if the package is abandoned or not */ public function isAbandoned(): bool; /** * If the package is abandoned and has a suggested replacement, this method returns it */ public function getReplacementPackage(): ?string; /** * @param bool|string $abandoned */ public function setAbandoned($abandoned): void; /** * Returns default base filename for archive */ public function getArchiveName(): ?string; /** * Sets default base filename for archive */ public function setArchiveName(string $name): void; /** * Returns a list of patterns to exclude from package archives * * @return string[] */ public function getArchiveExcludes(): array; /** * Sets a list of patterns to be excluded from archives * * @param string[] $excludes */ public function setArchiveExcludes(array $excludes): void; }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/RootPackage.php
src/Composer/Package/RootPackage.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; /** * The root package represents the project's composer.json and contains additional metadata * * @author Jordi Boggiano <j.boggiano@seld.be> */ class RootPackage extends CompletePackage implements RootPackageInterface { public const DEFAULT_PRETTY_VERSION = '1.0.0+no-version-set'; /** @var key-of<BasePackage::STABILITIES> */ protected $minimumStability = 'stable'; /** @var bool */ protected $preferStable = false; /** @var array<string, BasePackage::STABILITY_*> Map of package name to stability constant */ protected $stabilityFlags = []; /** @var mixed[] */ protected $config = []; /** @var array<string, string> Map of package name to reference/commit hash */ protected $references = []; /** @var list<array{package: string, version: string, alias: string, alias_normalized: string}> */ protected $aliases = []; /** * @inheritDoc */ public function setMinimumStability(string $minimumStability): void { $this->minimumStability = $minimumStability; } /** * @inheritDoc */ public function getMinimumStability(): string { return $this->minimumStability; } /** * @inheritDoc */ public function setStabilityFlags(array $stabilityFlags): void { $this->stabilityFlags = $stabilityFlags; } /** * @inheritDoc */ public function getStabilityFlags(): array { return $this->stabilityFlags; } /** * @inheritDoc */ public function setPreferStable(bool $preferStable): void { $this->preferStable = $preferStable; } /** * @inheritDoc */ public function getPreferStable(): bool { return $this->preferStable; } /** * @inheritDoc */ public function setConfig(array $config): void { $this->config = $config; } /** * @inheritDoc */ public function getConfig(): array { return $this->config; } /** * @inheritDoc */ public function setReferences(array $references): void { $this->references = $references; } /** * @inheritDoc */ public function getReferences(): array { return $this->references; } /** * @inheritDoc */ public function setAliases(array $aliases): void { $this->aliases = $aliases; } /** * @inheritDoc */ public function getAliases(): array { return $this->aliases; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/CompletePackage.php
src/Composer/Package/CompletePackage.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; /** * Package containing additional metadata that is not used by the solver * * @author Nils Adermann <naderman@naderman.de> */ class CompletePackage extends Package implements CompletePackageInterface { /** @var mixed[] */ protected $repositories = []; /** @var string[] */ protected $license = []; /** @var string[] */ protected $keywords = []; /** @var array<array{name?: string, homepage?: string, email?: string, role?: string}> */ protected $authors = []; /** @var ?string */ protected $description = null; /** @var ?string */ protected $homepage = null; /** @var array<string, string[]> Map of script name to array of handlers */ protected $scripts = []; /** @var array{issues?: string, forum?: string, wiki?: string, source?: string, email?: string, irc?: string, docs?: string, rss?: string, chat?: string, security?: string} */ protected $support = []; /** @var array<array{url?: string, type?: string}> */ protected $funding = []; /** @var bool|string */ protected $abandoned = false; /** @var ?string */ protected $archiveName = null; /** @var string[] */ protected $archiveExcludes = []; /** * @inheritDoc */ public function setScripts(array $scripts): void { $this->scripts = $scripts; } /** * @inheritDoc */ public function getScripts(): array { return $this->scripts; } /** * @inheritDoc */ public function setRepositories(array $repositories): void { $this->repositories = $repositories; } /** * @inheritDoc */ public function getRepositories(): array { return $this->repositories; } /** * @inheritDoc */ public function setLicense(array $license): void { $this->license = $license; } /** * @inheritDoc */ public function getLicense(): array { return $this->license; } /** * @inheritDoc */ public function setKeywords(array $keywords): void { $this->keywords = $keywords; } /** * @inheritDoc */ public function getKeywords(): array { return $this->keywords; } /** * @inheritDoc */ public function setAuthors(array $authors): void { $this->authors = $authors; } /** * @inheritDoc */ public function getAuthors(): array { return $this->authors; } /** * @inheritDoc */ public function setDescription(?string $description): void { $this->description = $description; } /** * @inheritDoc */ public function getDescription(): ?string { return $this->description; } /** * @inheritDoc */ public function setHomepage(?string $homepage): void { $this->homepage = $homepage; } /** * @inheritDoc */ public function getHomepage(): ?string { return $this->homepage; } /** * @inheritDoc */ public function setSupport(array $support): void { $this->support = $support; } /** * @inheritDoc */ public function getSupport(): array { return $this->support; } /** * @inheritDoc */ public function setFunding(array $funding): void { $this->funding = $funding; } /** * @inheritDoc */ public function getFunding(): array { return $this->funding; } /** * @inheritDoc */ public function isAbandoned(): bool { return (bool) $this->abandoned; } /** * @inheritDoc */ public function setAbandoned($abandoned): void { $this->abandoned = $abandoned; } /** * @inheritDoc */ public function getReplacementPackage(): ?string { return \is_string($this->abandoned) ? $this->abandoned : null; } /** * @inheritDoc */ public function setArchiveName(?string $name): void { $this->archiveName = $name; } /** * @inheritDoc */ public function getArchiveName(): ?string { return $this->archiveName; } /** * @inheritDoc */ public function setArchiveExcludes(array $excludes): void { $this->archiveExcludes = $excludes; } /** * @inheritDoc */ public function getArchiveExcludes(): array { return $this->archiveExcludes; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/PackageInterface.php
src/Composer/Package/PackageInterface.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; use Composer\Repository\RepositoryInterface; /** * Defines the essential information a package has that is used during solving/installation * * PackageInterface & derivatives are considered internal, you may use them in type hints but extending/implementing them is not recommended and not supported. Things may change without notice. * * @author Jordi Boggiano <j.boggiano@seld.be> * * @phpstan-type AutoloadRules array{psr-0?: array<string, string|string[]>, psr-4?: array<string, string|string[]>, classmap?: list<string>, files?: list<string>, exclude-from-classmap?: list<string>} * @phpstan-type DevAutoloadRules array{psr-0?: array<string, string|string[]>, psr-4?: array<string, string|string[]>, classmap?: list<string>, files?: list<string>} * @phpstan-type PhpExtConfig array{extension-name?: string, priority?: int, support-zts?: bool, support-nts?: bool, build-path?: string|null, download-url-method?: string, os-families?: non-empty-list<non-empty-string>, os-families-exclude?: non-empty-list<non-empty-string>, configure-options?: list<array{name: string, description?: string}>} */ interface PackageInterface { public const DISPLAY_SOURCE_REF_IF_DEV = 0; public const DISPLAY_SOURCE_REF = 1; public const DISPLAY_DIST_REF = 2; /** * Returns the package's name without version info, thus not a unique identifier * * @return string package name */ public function getName(): string; /** * Returns the package's pretty (i.e. with proper case) name * * @return string package name */ public function getPrettyName(): string; /** * Returns a set of names that could refer to this package * * No version or release type information should be included in any of the * names. Provided or replaced package names need to be returned as well. * * @param bool $provides Whether provided names should be included * * @return string[] An array of strings referring to this package */ public function getNames(bool $provides = true): array; /** * Allows the solver to set an id for this package to refer to it. */ public function setId(int $id): void; /** * Retrieves the package's id set through setId * * @return int The previously set package id */ public function getId(): int; /** * Returns whether the package is a development virtual package or a concrete one */ public function isDev(): bool; /** * Returns the package type, e.g. library * * @return string The package type */ public function getType(): string; /** * Returns the package targetDir property * * @return ?string The package targetDir */ public function getTargetDir(): ?string; /** * Returns the package extra data * * @return mixed[] The package extra data */ public function getExtra(): array; /** * Sets source from which this package was installed (source/dist). * * @param ?string $type source/dist * @phpstan-param 'source'|'dist'|null $type */ public function setInstallationSource(?string $type): void; /** * Returns source from which this package was installed (source/dist). * * @return ?string source/dist * @phpstan-return 'source'|'dist'|null */ public function getInstallationSource(): ?string; /** * Returns the repository type of this package, e.g. git, svn * * @return ?string The repository type */ public function getSourceType(): ?string; /** * Returns the repository url of this package, e.g. git://github.com/naderman/composer.git * * @return ?string The repository url */ public function getSourceUrl(): ?string; /** * Returns the repository urls of this package including mirrors, e.g. git://github.com/naderman/composer.git * * @return list<string> */ public function getSourceUrls(): array; /** * Returns the repository reference of this package, e.g. master, 1.0.0 or a commit hash for git * * @return ?string The repository reference */ public function getSourceReference(): ?string; /** * Returns the source mirrors of this package * * @return ?list<array{url: non-empty-string, preferred: bool}> */ public function getSourceMirrors(): ?array; /** * @param null|list<array{url: non-empty-string, preferred: bool}> $mirrors */ public function setSourceMirrors(?array $mirrors): void; /** * Returns the type of the distribution archive of this version, e.g. zip, tarball * * @return ?string The repository type */ public function getDistType(): ?string; /** * Returns the url of the distribution archive of this version * * @return ?non-empty-string */ public function getDistUrl(): ?string; /** * Returns the urls of the distribution archive of this version, including mirrors * * @return non-empty-string[] */ public function getDistUrls(): array; /** * Returns the reference of the distribution archive of this version, e.g. master, 1.0.0 or a commit hash for git */ public function getDistReference(): ?string; /** * Returns the sha1 checksum for the distribution archive of this version * * Can be an empty string which should be treated as null */ public function getDistSha1Checksum(): ?string; /** * Returns the dist mirrors of this package * * @return ?list<array{url: non-empty-string, preferred: bool}> */ public function getDistMirrors(): ?array; /** * @param null|list<array{url: non-empty-string, preferred: bool}> $mirrors */ public function setDistMirrors(?array $mirrors): void; /** * Returns the version of this package * * @return string version */ public function getVersion(): string; /** * Returns the pretty (i.e. non-normalized) version string of this package * * @return string version */ public function getPrettyVersion(): string; /** * Returns the pretty version string plus a git or hg commit hash of this package * * @see getPrettyVersion * * @param bool $truncate If the source reference is a sha1 hash, truncate it * @param int $displayMode One of the DISPLAY_ constants on this interface determining display of references * @return string version * * @phpstan-param self::DISPLAY_SOURCE_REF_IF_DEV|self::DISPLAY_SOURCE_REF|self::DISPLAY_DIST_REF $displayMode */ public function getFullPrettyVersion(bool $truncate = true, int $displayMode = self::DISPLAY_SOURCE_REF_IF_DEV): string; /** * Returns the release date of the package */ public function getReleaseDate(): ?\DateTimeInterface; /** * Returns the stability of this package: one of (dev, alpha, beta, RC, stable) * * @phpstan-return 'stable'|'RC'|'beta'|'alpha'|'dev' */ public function getStability(): string; /** * Returns a set of links to packages which need to be installed before * this package can be installed * * @return array<string, Link> A map of package links defining required packages, indexed by the require package's name */ public function getRequires(): array; /** * Returns a set of links to packages which must not be installed at the * same time as this package * * @return Link[] An array of package links defining conflicting packages */ public function getConflicts(): array; /** * Returns a set of links to virtual packages that are provided through * this package * * @return Link[] An array of package links defining provided packages */ public function getProvides(): array; /** * Returns a set of links to packages which can alternatively be * satisfied by installing this package * * @return Link[] An array of package links defining replaced packages */ public function getReplaces(): array; /** * Returns a set of links to packages which are required to develop * this package. These are installed if in dev mode. * * @return array<string, Link> A map of package links defining packages required for development, indexed by the require package's name */ public function getDevRequires(): array; /** * Returns a set of package names and reasons why they are useful in * combination with this package. * * @return array An array of package suggestions with descriptions * @phpstan-return array<string, string> */ public function getSuggests(): array; /** * Returns an associative array of autoloading rules * * {"<type>": {"<namespace": "<directory>"}} * * Type is either "psr-4", "psr-0", "classmap" or "files". Namespaces are mapped to * directories for autoloading using the type specified. * * @return array Mapping of autoloading rules * @phpstan-return AutoloadRules */ public function getAutoload(): array; /** * Returns an associative array of dev autoloading rules * * {"<type>": {"<namespace": "<directory>"}} * * Type is either "psr-4", "psr-0", "classmap" or "files". Namespaces are mapped to * directories for autoloading using the type specified. * * @return array Mapping of dev autoloading rules * @phpstan-return DevAutoloadRules */ public function getDevAutoload(): array; /** * Returns a list of directories which should get added to PHP's * include path. * * @return string[] */ public function getIncludePaths(): array; /** * Returns the settings for php extension packages * * * @phpstan-return PhpExtConfig|null */ public function getPhpExt(): ?array; /** * Stores a reference to the repository that owns the package */ public function setRepository(RepositoryInterface $repository): void; /** * Returns a reference to the repository that owns the package */ public function getRepository(): ?RepositoryInterface; /** * Returns the package binaries * * @return string[] */ public function getBinaries(): array; /** * Returns package unique name, constructed from name and version. */ public function getUniqueName(): string; /** * Returns the package notification url */ public function getNotificationUrl(): ?string; /** * Converts the package into a readable and unique string */ public function __toString(): string; /** * Converts the package into a pretty readable string */ public function getPrettyString(): string; public function isDefaultBranch(): bool; /** * Returns a list of options to download package dist files * * @return mixed[] */ public function getTransportOptions(): array; /** * Configures the list of options to download package dist files * * @param mixed[] $options */ public function setTransportOptions(array $options): void; public function setSourceReference(?string $reference): void; public function setDistUrl(?string $url): void; public function setDistType(?string $type): void; public function setDistReference(?string $reference): void; /** * Set dist and source references and update dist URL for ones that contain a reference */ public function setSourceDistReferences(string $reference): void; }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/AliasPackage.php
src/Composer/Package/AliasPackage.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; use Composer\Semver\Constraint\Constraint; use Composer\Package\Version\VersionParser; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class AliasPackage extends BasePackage { /** @var string */ protected $version; /** @var string */ protected $prettyVersion; /** @var bool */ protected $dev; /** @var bool */ protected $rootPackageAlias = false; /** * @var string * @phpstan-var 'stable'|'RC'|'beta'|'alpha'|'dev' */ protected $stability; /** @var bool */ protected $hasSelfVersionRequires = false; /** @var BasePackage */ protected $aliasOf; /** @var Link[] */ protected $requires; /** @var Link[] */ protected $devRequires; /** @var Link[] */ protected $conflicts; /** @var Link[] */ protected $provides; /** @var Link[] */ protected $replaces; /** * All descendants' constructors should call this parent constructor * * @param BasePackage $aliasOf The package this package is an alias of * @param string $version The version the alias must report * @param string $prettyVersion The alias's non-normalized version */ public function __construct(BasePackage $aliasOf, string $version, string $prettyVersion) { parent::__construct($aliasOf->getName()); $this->version = $version; $this->prettyVersion = $prettyVersion; $this->aliasOf = $aliasOf; $this->stability = VersionParser::parseStability($version); $this->dev = $this->stability === 'dev'; foreach (Link::$TYPES as $type) { $links = $aliasOf->{'get' . ucfirst($type)}(); $this->{$type} = $this->replaceSelfVersionDependencies($links, $type); } } /** * @return BasePackage */ public function getAliasOf() { return $this->aliasOf; } /** * @inheritDoc */ public function getVersion(): string { return $this->version; } /** * @inheritDoc */ public function getStability(): string { return $this->stability; } /** * @inheritDoc */ public function getPrettyVersion(): string { return $this->prettyVersion; } /** * @inheritDoc */ public function isDev(): bool { return $this->dev; } /** * @inheritDoc */ public function getRequires(): array { return $this->requires; } /** * @inheritDoc * @return array<string|int, Link> */ public function getConflicts(): array { return $this->conflicts; } /** * @inheritDoc * @return array<string|int, Link> */ public function getProvides(): array { return $this->provides; } /** * @inheritDoc * @return array<string|int, Link> */ public function getReplaces(): array { return $this->replaces; } /** * @inheritDoc */ public function getDevRequires(): array { return $this->devRequires; } /** * Stores whether this is an alias created by an aliasing in the requirements of the root package or not * * Use by the policy for sorting manually aliased packages first, see #576 */ public function setRootPackageAlias(bool $value): void { $this->rootPackageAlias = $value; } /** * @see setRootPackageAlias */ public function isRootPackageAlias(): bool { return $this->rootPackageAlias; } /** * @param Link[] $links * @param Link::TYPE_* $linkType * * @return Link[] */ protected function replaceSelfVersionDependencies(array $links, $linkType): array { // for self.version requirements, we use the original package's branch name instead, to avoid leaking the magic dev-master-alias to users $prettyVersion = $this->prettyVersion; if ($prettyVersion === VersionParser::DEFAULT_BRANCH_ALIAS) { $prettyVersion = $this->aliasOf->getPrettyVersion(); } if (\in_array($linkType, [Link::TYPE_CONFLICT, Link::TYPE_PROVIDE, Link::TYPE_REPLACE], true)) { $newLinks = []; foreach ($links as $link) { // link is self.version, but must be replacing also the replaced version if ('self.version' === $link->getPrettyConstraint()) { $newLinks[] = new Link($link->getSource(), $link->getTarget(), $constraint = new Constraint('=', $this->version), $linkType, $prettyVersion); $constraint->setPrettyString($prettyVersion); } } $links = array_merge($links, $newLinks); } else { foreach ($links as $index => $link) { if ('self.version' === $link->getPrettyConstraint()) { if ($linkType === Link::TYPE_REQUIRE) { $this->hasSelfVersionRequires = true; } $links[$index] = new Link($link->getSource(), $link->getTarget(), $constraint = new Constraint('=', $this->version), $linkType, $prettyVersion); $constraint->setPrettyString($prettyVersion); } } } return $links; } public function hasSelfVersionRequires(): bool { return $this->hasSelfVersionRequires; } public function __toString(): string { return parent::__toString().' ('.($this->rootPackageAlias ? 'root ' : ''). 'alias of '.$this->aliasOf->getVersion().')'; } /*************************************** * Wrappers around the aliased package * ***************************************/ public function getType(): string { return $this->aliasOf->getType(); } public function getTargetDir(): ?string { return $this->aliasOf->getTargetDir(); } public function getExtra(): array { return $this->aliasOf->getExtra(); } public function setInstallationSource(?string $type): void { $this->aliasOf->setInstallationSource($type); } public function getInstallationSource(): ?string { return $this->aliasOf->getInstallationSource(); } public function getSourceType(): ?string { return $this->aliasOf->getSourceType(); } public function getSourceUrl(): ?string { return $this->aliasOf->getSourceUrl(); } public function getSourceUrls(): array { return $this->aliasOf->getSourceUrls(); } public function getSourceReference(): ?string { return $this->aliasOf->getSourceReference(); } public function setSourceReference(?string $reference): void { $this->aliasOf->setSourceReference($reference); } public function setSourceMirrors(?array $mirrors): void { $this->aliasOf->setSourceMirrors($mirrors); } public function getSourceMirrors(): ?array { return $this->aliasOf->getSourceMirrors(); } public function getDistType(): ?string { return $this->aliasOf->getDistType(); } public function getDistUrl(): ?string { return $this->aliasOf->getDistUrl(); } public function getDistUrls(): array { return $this->aliasOf->getDistUrls(); } public function getDistReference(): ?string { return $this->aliasOf->getDistReference(); } public function setDistReference(?string $reference): void { $this->aliasOf->setDistReference($reference); } public function getDistSha1Checksum(): ?string { return $this->aliasOf->getDistSha1Checksum(); } public function setTransportOptions(array $options): void { $this->aliasOf->setTransportOptions($options); } public function getTransportOptions(): array { return $this->aliasOf->getTransportOptions(); } public function setDistMirrors(?array $mirrors): void { $this->aliasOf->setDistMirrors($mirrors); } public function getDistMirrors(): ?array { return $this->aliasOf->getDistMirrors(); } public function getAutoload(): array { return $this->aliasOf->getAutoload(); } public function getDevAutoload(): array { return $this->aliasOf->getDevAutoload(); } public function getIncludePaths(): array { return $this->aliasOf->getIncludePaths(); } public function getPhpExt(): ?array { return $this->aliasOf->getPhpExt(); } public function getReleaseDate(): ?\DateTimeInterface { return $this->aliasOf->getReleaseDate(); } public function getBinaries(): array { return $this->aliasOf->getBinaries(); } public function getSuggests(): array { return $this->aliasOf->getSuggests(); } public function getNotificationUrl(): ?string { return $this->aliasOf->getNotificationUrl(); } public function isDefaultBranch(): bool { return $this->aliasOf->isDefaultBranch(); } public function setDistUrl(?string $url): void { $this->aliasOf->setDistUrl($url); } public function setDistType(?string $type): void { $this->aliasOf->setDistType($type); } public function setSourceDistReferences(string $reference): void { $this->aliasOf->setSourceDistReferences($reference); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/RootAliasPackage.php
src/Composer/Package/RootAliasPackage.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; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterface { /** @var RootPackage */ protected $aliasOf; /** * All descendants' constructors should call this parent constructor * * @param RootPackage $aliasOf The package this package is an alias of * @param string $version The version the alias must report * @param string $prettyVersion The alias's non-normalized version */ public function __construct(RootPackage $aliasOf, string $version, string $prettyVersion) { parent::__construct($aliasOf, $version, $prettyVersion); } /** * @return RootPackage */ public function getAliasOf() { return $this->aliasOf; } /** * @inheritDoc */ public function getAliases(): array { return $this->aliasOf->getAliases(); } /** * @inheritDoc */ public function getMinimumStability(): string { return $this->aliasOf->getMinimumStability(); } /** * @inheritDoc */ public function getStabilityFlags(): array { return $this->aliasOf->getStabilityFlags(); } /** * @inheritDoc */ public function getReferences(): array { return $this->aliasOf->getReferences(); } /** * @inheritDoc */ public function getPreferStable(): bool { return $this->aliasOf->getPreferStable(); } /** * @inheritDoc */ public function getConfig(): array { return $this->aliasOf->getConfig(); } /** * @inheritDoc */ public function setRequires(array $requires): void { $this->requires = $this->replaceSelfVersionDependencies($requires, Link::TYPE_REQUIRE); $this->aliasOf->setRequires($requires); } /** * @inheritDoc */ public function setDevRequires(array $devRequires): void { $this->devRequires = $this->replaceSelfVersionDependencies($devRequires, Link::TYPE_DEV_REQUIRE); $this->aliasOf->setDevRequires($devRequires); } /** * @inheritDoc */ public function setConflicts(array $conflicts): void { $this->conflicts = $this->replaceSelfVersionDependencies($conflicts, Link::TYPE_CONFLICT); $this->aliasOf->setConflicts($conflicts); } /** * @inheritDoc */ public function setProvides(array $provides): void { $this->provides = $this->replaceSelfVersionDependencies($provides, Link::TYPE_PROVIDE); $this->aliasOf->setProvides($provides); } /** * @inheritDoc */ public function setReplaces(array $replaces): void { $this->replaces = $this->replaceSelfVersionDependencies($replaces, Link::TYPE_REPLACE); $this->aliasOf->setReplaces($replaces); } /** * @inheritDoc */ public function setAutoload(array $autoload): void { $this->aliasOf->setAutoload($autoload); } /** * @inheritDoc */ public function setDevAutoload(array $devAutoload): void { $this->aliasOf->setDevAutoload($devAutoload); } /** * @inheritDoc */ public function setStabilityFlags(array $stabilityFlags): void { $this->aliasOf->setStabilityFlags($stabilityFlags); } /** * @inheritDoc */ public function setMinimumStability(string $minimumStability): void { $this->aliasOf->setMinimumStability($minimumStability); } /** * @inheritDoc */ public function setPreferStable(bool $preferStable): void { $this->aliasOf->setPreferStable($preferStable); } /** * @inheritDoc */ public function setConfig(array $config): void { $this->aliasOf->setConfig($config); } /** * @inheritDoc */ public function setReferences(array $references): void { $this->aliasOf->setReferences($references); } /** * @inheritDoc */ public function setAliases(array $aliases): void { $this->aliasOf->setAliases($aliases); } /** * @inheritDoc */ public function setSuggests(array $suggests): void { $this->aliasOf->setSuggests($suggests); } /** * @inheritDoc */ public function setExtra(array $extra): void { $this->aliasOf->setExtra($extra); } public function __clone() { parent::__clone(); $this->aliasOf = clone $this->aliasOf; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/BasePackage.php
src/Composer/Package/BasePackage.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; use Composer\Repository\RepositoryInterface; use Composer\Repository\PlatformRepository; /** * Base class for packages providing name storage and default match implementation * * @author Nils Adermann <naderman@naderman.de> */ abstract class BasePackage implements PackageInterface { /** * @phpstan-var array<non-empty-string, array{description: string, method: Link::TYPE_*}> * @internal */ public static $supportedLinkTypes = [ 'require' => ['description' => 'requires', 'method' => Link::TYPE_REQUIRE], 'conflict' => ['description' => 'conflicts', 'method' => Link::TYPE_CONFLICT], 'provide' => ['description' => 'provides', 'method' => Link::TYPE_PROVIDE], 'replace' => ['description' => 'replaces', 'method' => Link::TYPE_REPLACE], 'require-dev' => ['description' => 'requires (for development)', 'method' => Link::TYPE_DEV_REQUIRE], ]; public const STABILITY_STABLE = 0; public const STABILITY_RC = 5; public const STABILITY_BETA = 10; public const STABILITY_ALPHA = 15; public const STABILITY_DEV = 20; public const STABILITIES = [ 'stable' => self::STABILITY_STABLE, 'RC' => self::STABILITY_RC, 'beta' => self::STABILITY_BETA, 'alpha' => self::STABILITY_ALPHA, 'dev' => self::STABILITY_DEV, ]; /** * @deprecated * @readonly * @var array<key-of<BasePackage::STABILITIES>, self::STABILITY_*> * @phpstan-ignore property.readOnlyByPhpDocDefaultValue */ public static $stabilities = self::STABILITIES; /** * READ-ONLY: The package id, public for fast access in dependency solver * @var int * @internal */ public $id; /** @var string */ protected $name; /** @var string */ protected $prettyName; /** @var ?RepositoryInterface */ protected $repository = null; /** * All descendants' constructors should call this parent constructor * * @param string $name The package's name */ public function __construct(string $name) { $this->prettyName = $name; $this->name = strtolower($name); $this->id = -1; } /** * @inheritDoc */ public function getName(): string { return $this->name; } /** * @inheritDoc */ public function getPrettyName(): string { return $this->prettyName; } /** * @inheritDoc */ public function getNames($provides = true): array { $names = [ $this->getName() => true, ]; if ($provides) { foreach ($this->getProvides() as $link) { $names[$link->getTarget()] = true; } } foreach ($this->getReplaces() as $link) { $names[$link->getTarget()] = true; } return array_keys($names); } /** * @inheritDoc */ public function setId(int $id): void { $this->id = $id; } /** * @inheritDoc */ public function getId(): int { return $this->id; } /** * @inheritDoc */ public function setRepository(RepositoryInterface $repository): void { if ($this->repository && $repository !== $this->repository) { throw new \LogicException(sprintf( 'Package "%s" cannot be added to repository "%s" as it is already in repository "%s".', $this->getPrettyName(), $repository->getRepoName(), $this->repository->getRepoName() )); } $this->repository = $repository; } /** * @inheritDoc */ public function getRepository(): ?RepositoryInterface { return $this->repository; } /** * checks if this package is a platform package */ public function isPlatform(): bool { return $this->getRepository() instanceof PlatformRepository; } /** * Returns package unique name, constructed from name, version and release type. */ public function getUniqueName(): string { return $this->getName().'-'.$this->getVersion(); } public function equals(PackageInterface $package): bool { $self = $this; if ($this instanceof AliasPackage) { $self = $this->getAliasOf(); } if ($package instanceof AliasPackage) { $package = $package->getAliasOf(); } return $package === $self; } /** * Converts the package into a readable and unique string */ public function __toString(): string { return $this->getUniqueName(); } public function getPrettyString(): string { return $this->getPrettyName().' '.$this->getPrettyVersion(); } /** * @inheritDoc */ public function getFullPrettyVersion(bool $truncate = true, int $displayMode = PackageInterface::DISPLAY_SOURCE_REF_IF_DEV): string { if ( $displayMode === PackageInterface::DISPLAY_SOURCE_REF_IF_DEV && ( !$this->isDev() || ( !\in_array($this->getSourceType(), ['hg', 'git']) && ((string) $this->getSourceType() !== '' || (string) $this->getDistReference() === '') ) ) ) { return $this->getPrettyVersion(); } switch ($displayMode) { case PackageInterface::DISPLAY_SOURCE_REF_IF_DEV: $reference = (string) $this->getSourceReference() !== '' ? $this->getSourceReference() : $this->getDistReference(); break; case PackageInterface::DISPLAY_SOURCE_REF: $reference = $this->getSourceReference(); break; case PackageInterface::DISPLAY_DIST_REF: $reference = $this->getDistReference(); break; default: throw new \UnexpectedValueException('Display mode '.$displayMode.' is not supported'); } if (null === $reference) { return $this->getPrettyVersion(); } // if source reference is a sha1 hash -- truncate if ($truncate && \strlen($reference) === 40 && $this->getSourceType() !== 'svn') { return $this->getPrettyVersion() . ' ' . substr($reference, 0, 7); } return $this->getPrettyVersion() . ' ' . $reference; } /** * @phpstan-return self::STABILITY_* */ public function getStabilityPriority(): int { return self::STABILITIES[$this->getStability()]; } public function __clone() { $this->repository = null; $this->id = -1; } /** * Build a regexp from a package name, expanding * globs as required * * @param non-empty-string $wrap Wrap the cleaned string by the given string * @return non-empty-string */ public static function packageNameToRegexp(string $allowPattern, string $wrap = '{^%s$}i'): string { $cleanedAllowPattern = str_replace('\\*', '.*', preg_quote($allowPattern)); return sprintf($wrap, $cleanedAllowPattern); } /** * Build a regexp from package names, expanding * globs as required * * @param string[] $packageNames * @param non-empty-string $wrap * @return non-empty-string */ public static function packageNamesToRegexp(array $packageNames, string $wrap = '{^(?:%s)$}iD'): string { $packageNames = array_map( static function ($packageName): string { return BasePackage::packageNameToRegexp($packageName, '%s'); }, $packageNames ); return sprintf($wrap, implode('|', $packageNames)); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Package.php
src/Composer/Package/Package.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; use Composer\Package\Version\VersionParser; use Composer\Pcre\Preg; use Composer\Util\ComposerMirror; /** * Core package definitions that are needed to resolve dependencies and install packages * * @author Nils Adermann <naderman@naderman.de> * * @phpstan-import-type AutoloadRules from PackageInterface * @phpstan-import-type DevAutoloadRules from PackageInterface * @phpstan-import-type PhpExtConfig from PackageInterface */ class Package extends BasePackage { /** @var string */ protected $type; /** @var ?string */ protected $targetDir; /** @var 'source'|'dist'|null */ protected $installationSource; /** @var ?string */ protected $sourceType; /** @var ?string */ protected $sourceUrl; /** @var ?string */ protected $sourceReference; /** @var ?list<array{url: non-empty-string, preferred: bool}> */ protected $sourceMirrors; /** @var ?non-empty-string */ protected $distType; /** @var ?non-empty-string */ protected $distUrl; /** @var ?string */ protected $distReference; /** @var ?string */ protected $distSha1Checksum; /** @var ?list<array{url: non-empty-string, preferred: bool}> */ protected $distMirrors; /** @var string */ protected $version; /** @var string */ protected $prettyVersion; /** @var ?\DateTimeInterface */ protected $releaseDate; /** @var mixed[] */ protected $extra = []; /** @var string[] */ protected $binaries = []; /** @var bool */ protected $dev; /** * @var string * @phpstan-var 'stable'|'RC'|'beta'|'alpha'|'dev' */ protected $stability; /** @var ?string */ protected $notificationUrl; /** @var array<string, Link> */ protected $requires = []; /** @var array<string, Link> */ protected $conflicts = []; /** @var array<string, Link> */ protected $provides = []; /** @var array<string, Link> */ protected $replaces = []; /** @var array<string, Link> */ protected $devRequires = []; /** @var array<string, string> */ protected $suggests = []; /** * @var array * @phpstan-var AutoloadRules */ protected $autoload = []; /** * @var array * @phpstan-var DevAutoloadRules */ protected $devAutoload = []; /** @var string[] */ protected $includePaths = []; /** @var bool */ protected $isDefaultBranch = false; /** @var mixed[] */ protected $transportOptions = []; /** * @var array|null * @phpstan-var PhpExtConfig|null */ protected $phpExt = null; /** * Creates a new in memory package. * * @param string $name The package's name * @param string $version The package's version * @param string $prettyVersion The package's non-normalized version */ public function __construct(string $name, string $version, string $prettyVersion) { parent::__construct($name); $this->version = $version; $this->prettyVersion = $prettyVersion; $this->stability = VersionParser::parseStability($version); $this->dev = $this->stability === 'dev'; } /** * @inheritDoc */ public function isDev(): bool { return $this->dev; } public function setType(string $type): void { $this->type = $type; } /** * @inheritDoc */ public function getType(): string { return $this->type ?: 'library'; } /** * @inheritDoc */ public function getStability(): string { return $this->stability; } public function setTargetDir(?string $targetDir): void { $this->targetDir = $targetDir; } /** * @inheritDoc */ public function getTargetDir(): ?string { if (null === $this->targetDir) { return null; } return ltrim(Preg::replace('{ (?:^|[\\\\/]+) \.\.? (?:[\\\\/]+|$) (?:\.\.? (?:[\\\\/]+|$) )*}x', '/', $this->targetDir), '/'); } /** * @param mixed[] $extra */ public function setExtra(array $extra): void { $this->extra = $extra; } /** * @inheritDoc */ public function getExtra(): array { return $this->extra; } /** * @param string[] $binaries */ public function setBinaries(array $binaries): void { $this->binaries = $binaries; } /** * @inheritDoc */ public function getBinaries(): array { return $this->binaries; } /** * @inheritDoc */ public function setInstallationSource(?string $type): void { $this->installationSource = $type; } /** * @inheritDoc */ public function getInstallationSource(): ?string { return $this->installationSource; } public function setSourceType(?string $type): void { $this->sourceType = $type; } /** * @inheritDoc */ public function getSourceType(): ?string { return $this->sourceType; } public function setSourceUrl(?string $url): void { $this->sourceUrl = $url; } /** * @inheritDoc */ public function getSourceUrl(): ?string { return $this->sourceUrl; } public function setSourceReference(?string $reference): void { $this->sourceReference = $reference; } /** * @inheritDoc */ public function getSourceReference(): ?string { return $this->sourceReference; } public function setSourceMirrors(?array $mirrors): void { $this->sourceMirrors = $mirrors; } /** * @inheritDoc */ public function getSourceMirrors(): ?array { return $this->sourceMirrors; } /** * @inheritDoc */ public function getSourceUrls(): array { return $this->getUrls($this->sourceUrl, $this->sourceMirrors, $this->sourceReference, $this->sourceType, 'source'); } public function setDistType(?string $type): void { $this->distType = $type === '' ? null : $type; } /** * @inheritDoc */ public function getDistType(): ?string { return $this->distType; } public function setDistUrl(?string $url): void { $this->distUrl = $url === '' ? null : $url; } /** * @inheritDoc */ public function getDistUrl(): ?string { return $this->distUrl; } public function setDistReference(?string $reference): void { $this->distReference = $reference; } /** * @inheritDoc */ public function getDistReference(): ?string { return $this->distReference; } public function setDistSha1Checksum(?string $sha1checksum): void { $this->distSha1Checksum = $sha1checksum; } /** * @inheritDoc */ public function getDistSha1Checksum(): ?string { return $this->distSha1Checksum; } public function setDistMirrors(?array $mirrors): void { $this->distMirrors = $mirrors; } /** * @inheritDoc */ public function getDistMirrors(): ?array { return $this->distMirrors; } /** * @inheritDoc */ public function getDistUrls(): array { return $this->getUrls($this->distUrl, $this->distMirrors, $this->distReference, $this->distType, 'dist'); } /** * @inheritDoc */ public function getTransportOptions(): array { return $this->transportOptions; } /** * @inheritDoc */ public function setTransportOptions(array $options): void { $this->transportOptions = $options; } /** * @inheritDoc */ public function getVersion(): string { return $this->version; } /** * @inheritDoc */ public function getPrettyVersion(): string { return $this->prettyVersion; } public function setReleaseDate(?\DateTimeInterface $releaseDate): void { $this->releaseDate = $releaseDate; } /** * @inheritDoc */ public function getReleaseDate(): ?\DateTimeInterface { return $this->releaseDate; } /** * Set the required packages * * @param array<string, Link> $requires A set of package links */ public function setRequires(array $requires): void { if (isset($requires[0])) { // @phpstan-ignore-line $requires = $this->convertLinksToMap($requires, 'setRequires'); } $this->requires = $requires; } /** * @inheritDoc */ public function getRequires(): array { return $this->requires; } /** * Set the conflicting packages * * @param array<string, Link> $conflicts A set of package links */ public function setConflicts(array $conflicts): void { if (isset($conflicts[0])) { // @phpstan-ignore-line $conflicts = $this->convertLinksToMap($conflicts, 'setConflicts'); } $this->conflicts = $conflicts; } /** * @inheritDoc * @return array<string, Link> */ public function getConflicts(): array { return $this->conflicts; } /** * Set the provided virtual packages * * @param array<string, Link> $provides A set of package links */ public function setProvides(array $provides): void { if (isset($provides[0])) { // @phpstan-ignore-line $provides = $this->convertLinksToMap($provides, 'setProvides'); } $this->provides = $provides; } /** * @inheritDoc * @return array<string, Link> */ public function getProvides(): array { return $this->provides; } /** * Set the packages this one replaces * * @param array<string, Link> $replaces A set of package links */ public function setReplaces(array $replaces): void { if (isset($replaces[0])) { // @phpstan-ignore-line $replaces = $this->convertLinksToMap($replaces, 'setReplaces'); } $this->replaces = $replaces; } /** * @inheritDoc * @return array<string, Link> */ public function getReplaces(): array { return $this->replaces; } /** * Set the recommended packages * * @param array<string, Link> $devRequires A set of package links */ public function setDevRequires(array $devRequires): void { if (isset($devRequires[0])) { // @phpstan-ignore-line $devRequires = $this->convertLinksToMap($devRequires, 'setDevRequires'); } $this->devRequires = $devRequires; } /** * @inheritDoc */ public function getDevRequires(): array { return $this->devRequires; } /** * Set the suggested packages * * @param array<string, string> $suggests A set of package names/comments */ public function setSuggests(array $suggests): void { $this->suggests = $suggests; } /** * @inheritDoc */ public function getSuggests(): array { return $this->suggests; } /** * Set the autoload mapping * * @param array $autoload Mapping of autoloading rules * * @phpstan-param AutoloadRules $autoload */ public function setAutoload(array $autoload): void { $this->autoload = $autoload; } /** * @inheritDoc */ public function getAutoload(): array { return $this->autoload; } /** * Set the dev autoload mapping * * @param array $devAutoload Mapping of dev autoloading rules * * @phpstan-param DevAutoloadRules $devAutoload */ public function setDevAutoload(array $devAutoload): void { $this->devAutoload = $devAutoload; } /** * @inheritDoc */ public function getDevAutoload(): array { return $this->devAutoload; } /** * Sets the list of paths added to PHP's include path. * * @param string[] $includePaths List of directories. */ public function setIncludePaths(array $includePaths): void { $this->includePaths = $includePaths; } /** * @inheritDoc */ public function getIncludePaths(): array { return $this->includePaths; } /** * Sets the settings for php extension packages * * * @phpstan-param PhpExtConfig|null $phpExt */ public function setPhpExt(?array $phpExt): void { $this->phpExt = $phpExt; } /** * @inheritDoc */ public function getPhpExt(): ?array { return $this->phpExt; } /** * Sets the notification URL */ public function setNotificationUrl(string $notificationUrl): void { $this->notificationUrl = $notificationUrl; } /** * @inheritDoc */ public function getNotificationUrl(): ?string { return $this->notificationUrl; } public function setIsDefaultBranch(bool $defaultBranch): void { $this->isDefaultBranch = $defaultBranch; } /** * @inheritDoc */ public function isDefaultBranch(): bool { return $this->isDefaultBranch; } /** * @inheritDoc */ public function setSourceDistReferences(string $reference): void { $this->setSourceReference($reference); // only bitbucket, github and gitlab have auto generated dist URLs that easily allow replacing the reference in the dist URL // TODO generalize this a bit for self-managed/on-prem versions? Some kind of replace token in dist urls which allow this? if ( $this->getDistUrl() !== null && Preg::isMatch('{^https?://(?:(?:www\.)?bitbucket\.org|(api\.)?github\.com|(?:www\.)?gitlab\.com)/}i', $this->getDistUrl()) ) { $this->setDistReference($reference); $this->setDistUrl(Preg::replace('{(?<=/|sha=)[a-f0-9]{40}(?=/|$)}i', $reference, $this->getDistUrl())); } elseif ($this->getDistReference()) { // update the dist reference if there was one, but if none was provided ignore it $this->setDistReference($reference); } } /** * Replaces current version and pretty version with passed values. * It also sets stability. * * @param string $version The package's normalized version * @param string $prettyVersion The package's non-normalized version */ public function replaceVersion(string $version, string $prettyVersion): void { $this->version = $version; $this->prettyVersion = $prettyVersion; $this->stability = VersionParser::parseStability($version); $this->dev = $this->stability === 'dev'; } /** * @param mixed[]|null $mirrors * * @return list<non-empty-string> * * @phpstan-param list<array{url: non-empty-string, preferred: bool}>|null $mirrors */ protected function getUrls(?string $url, ?array $mirrors, ?string $ref, ?string $type, string $urlType): array { if (!$url) { return []; } if ($urlType === 'dist' && false !== strpos($url, '%')) { $url = ComposerMirror::processUrl($url, $this->name, $this->version, $ref, $type, $this->prettyVersion); } $urls = [$url]; if ($mirrors) { foreach ($mirrors as $mirror) { if ($urlType === 'dist') { $mirrorUrl = ComposerMirror::processUrl($mirror['url'], $this->name, $this->version, $ref, $type, $this->prettyVersion); } elseif ($urlType === 'source' && $type === 'git') { $mirrorUrl = ComposerMirror::processGitUrl($mirror['url'], $this->name, $url, $type); } elseif ($urlType === 'source' && $type === 'hg') { $mirrorUrl = ComposerMirror::processHgUrl($mirror['url'], $this->name, $url, $type); } else { continue; } if (!\in_array($mirrorUrl, $urls)) { $func = $mirror['preferred'] ? 'array_unshift' : 'array_push'; $func($urls, $mirrorUrl); } } } return $urls; } /** * @param array<int, Link> $links * @return array<string, Link> */ private function convertLinksToMap(array $links, string $source): array { trigger_error('Package::'.$source.' must be called with a map of lowercased package name => Link object, got a indexed array, this is deprecated and you should fix your usage.'); $newLinks = []; foreach ($links as $link) { $newLinks[$link->getTarget()] = $link; } return $newLinks; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Archiver/ArchiveManager.php
src/Composer/Package/Archiver/ArchiveManager.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\Downloader\DownloadManager; use Composer\Package\RootPackageInterface; use Composer\Pcre\Preg; use Composer\Util\Filesystem; use Composer\Util\Loop; use Composer\Util\SyncHelper; use Composer\Json\JsonFile; use Composer\Package\CompletePackageInterface; /** * @author Matthieu Moquet <matthieu@moquet.net> * @author Till Klampaeckel <till@php.net> */ class ArchiveManager { /** @var DownloadManager */ protected $downloadManager; /** @var Loop */ protected $loop; /** * @var ArchiverInterface[] */ protected $archivers = []; /** * @var bool */ protected $overwriteFiles = true; /** * @param DownloadManager $downloadManager A manager used to download package sources */ public function __construct(DownloadManager $downloadManager, Loop $loop) { $this->downloadManager = $downloadManager; $this->loop = $loop; } public function addArchiver(ArchiverInterface $archiver): void { $this->archivers[] = $archiver; } /** * Set whether existing archives should be overwritten * * @param bool $overwriteFiles New setting * * @return $this */ public function setOverwriteFiles(bool $overwriteFiles): self { $this->overwriteFiles = $overwriteFiles; return $this; } /** * @return array<string, string> * @internal */ public function getPackageFilenameParts(CompletePackageInterface $package): array { $baseName = $package->getArchiveName(); if (null === $baseName) { $baseName = Preg::replace('#[^a-z0-9-_]#i', '-', $package->getName()); } $parts = [ 'base' => $baseName, ]; $distReference = $package->getDistReference(); if (null !== $distReference && Preg::isMatch('{^[a-f0-9]{40}$}', $distReference)) { $parts['dist_reference'] = $distReference; $parts['dist_type'] = $package->getDistType(); } else { $parts['version'] = $package->getPrettyVersion(); $parts['dist_reference'] = $distReference; } $sourceReference = $package->getSourceReference(); if (null !== $sourceReference) { $parts['source_reference'] = substr(hash('sha1', $sourceReference), 0, 6); } $parts = array_filter($parts, static function (?string $part) { return $part !== null; }); foreach ($parts as $key => $part) { $parts[$key] = str_replace('/', '-', $part); } return $parts; } /** * @param array<string, string> $parts * * @internal */ public function getPackageFilenameFromParts(array $parts): string { return implode('-', $parts); } /** * Generate a distinct filename for a particular version of a package. * * @param CompletePackageInterface $package The package to get a name for * * @return string A filename without an extension */ public function getPackageFilename(CompletePackageInterface $package): string { return $this->getPackageFilenameFromParts($this->getPackageFilenameParts($package)); } /** * Create an archive of the specified package. * * @param CompletePackageInterface $package The package to archive * @param string $format The format of the archive (zip, tar, ...) * @param string $targetDir The directory where to build the archive * @param string|null $fileName The relative file name to use for the archive, or null to generate * the package name. Note that the format will be appended to this name * @param bool $ignoreFilters Ignore filters when looking for files in the package * @throws \InvalidArgumentException * @throws \RuntimeException * @return string The path of the created archive */ public function archive(CompletePackageInterface $package, string $format, string $targetDir, ?string $fileName = null, bool $ignoreFilters = false): string { if (empty($format)) { throw new \InvalidArgumentException('Format must be specified'); } // Search for the most appropriate archiver $usableArchiver = null; foreach ($this->archivers as $archiver) { if ($archiver->supports($format, $package->getSourceType())) { $usableArchiver = $archiver; break; } } // Checks the format/source type are supported before downloading the package if (null === $usableArchiver) { throw new \RuntimeException(sprintf('No archiver found to support %s format', $format)); } $filesystem = new Filesystem(); if ($package instanceof RootPackageInterface) { $sourcePath = realpath('.'); } else { // Directory used to download the sources $sourcePath = sys_get_temp_dir().'/composer_archive'.bin2hex(random_bytes(5)); $filesystem->ensureDirectoryExists($sourcePath); try { // Download sources $promise = $this->downloadManager->download($package, $sourcePath); SyncHelper::await($this->loop, $promise); $promise = $this->downloadManager->install($package, $sourcePath); SyncHelper::await($this->loop, $promise); } catch (\Exception $e) { $filesystem->removeDirectory($sourcePath); throw $e; } // Check exclude from downloaded composer.json if (file_exists($composerJsonPath = $sourcePath.'/composer.json')) { $jsonFile = new JsonFile($composerJsonPath); $jsonData = $jsonFile->read(); if (!empty($jsonData['archive']['name'])) { $package->setArchiveName($jsonData['archive']['name']); } if (!empty($jsonData['archive']['exclude'])) { $package->setArchiveExcludes($jsonData['archive']['exclude']); } } } $supportedFormats = $this->getSupportedFormats(); $packageNameParts = null === $fileName ? $this->getPackageFilenameParts($package) : ['base' => $fileName]; $packageName = $this->getPackageFilenameFromParts($packageNameParts); $excludePatterns = $this->buildExcludePatterns($packageNameParts, $supportedFormats); // Archive filename $filesystem->ensureDirectoryExists($targetDir); $target = realpath($targetDir).'/'.$packageName.'.'.$format; $filesystem->ensureDirectoryExists(dirname($target)); if (!$this->overwriteFiles && file_exists($target)) { return $target; } // Create the archive $tempTarget = sys_get_temp_dir().'/composer_archive'.bin2hex(random_bytes(5)).'.'.$format; $filesystem->ensureDirectoryExists(dirname($tempTarget)); $archivePath = $usableArchiver->archive( $sourcePath, $tempTarget, $format, array_merge($excludePatterns, $package->getArchiveExcludes()), $ignoreFilters ); $filesystem->rename($archivePath, $target); // cleanup temporary download if (!$package instanceof RootPackageInterface) { $filesystem->removeDirectory($sourcePath); } $filesystem->remove($tempTarget); return $target; } /** * @param string[] $parts * @param string[] $formats * * @return string[] */ private function buildExcludePatterns(array $parts, array $formats): array { $base = $parts['base']; if (count($parts) > 1) { $base .= '-*'; } $patterns = []; foreach ($formats as $format) { $patterns[] = "$base.$format"; } return $patterns; } /** * @return string[] */ private function getSupportedFormats(): array { // The problem is that the \Composer\Package\Archiver\ArchiverInterface // doesn't provide method to get the supported formats. // Supported formats are also hard-coded into the description of the // --format option. // See \Composer\Command\ArchiveCommand::configure(). $formats = []; foreach ($this->archivers as $archiver) { $items = []; switch (get_class($archiver)) { case ZipArchiver::class: $items = ['zip']; break; case PharArchiver::class: $items = ['zip', 'tar', 'tar.gz', 'tar.bz2']; break; } $formats = array_merge($formats, $items); } return array_unique($formats); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Archiver/ZipArchiver.php
src/Composer/Package/Archiver/ZipArchiver.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\Util\Filesystem; use Composer\Util\Platform; use ZipArchive; /** * @author Jan Prieser <jan@prieser.net> */ class ZipArchiver implements ArchiverInterface { /** @var array<string, bool> */ protected static $formats = [ 'zip' => true, ]; /** * @inheritDoc */ public function archive(string $sources, string $target, string $format, array $excludes = [], bool $ignoreFilters = false): string { $fs = new Filesystem(); $sourcesRealpath = realpath($sources); if (false !== $sourcesRealpath) { $sources = $sourcesRealpath; } unset($sourcesRealpath); $sources = $fs->normalizePath($sources); $zip = new ZipArchive(); $res = $zip->open($target, ZipArchive::CREATE); if ($res === true) { $files = new ArchivableFilesFinder($sources, $excludes, $ignoreFilters); foreach ($files as $file) { /** @var \Symfony\Component\Finder\SplFileInfo $file */ $filepath = $file->getPathname(); $relativePath = $file->getRelativePathname(); if (Platform::isWindows()) { $relativePath = strtr($relativePath, '\\', '/'); } if ($file->isDir()) { $zip->addEmptyDir($relativePath); } else { $zip->addFile($filepath, $relativePath); } /** * setExternalAttributesName() is only available with libzip 0.11.2 or above */ if (method_exists($zip, 'setExternalAttributesName')) { $perms = fileperms($filepath); /** * Ensure to preserve the permission umasks for the filepath in the archive. */ $zip->setExternalAttributesName($relativePath, ZipArchive::OPSYS_UNIX, $perms << 16); } } if ($zip->close()) { if (!file_exists($target)) { // 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); } return $target; } } $message = sprintf( "Could not create archive '%s' from '%s': %s", $target, $sources, $zip->getStatusString() ); throw new \RuntimeException($message); } /** * @inheritDoc */ public function supports(string $format, ?string $sourceType): bool { return isset(static::$formats[$format]) && $this->compressionAvailable(); } private function compressionAvailable(): bool { return class_exists('ZipArchive'); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Archiver/ArchivableFilesFinder.php
src/Composer/Package/Archiver/ArchivableFilesFinder.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; use Composer\Util\Filesystem; use FilesystemIterator; use FilterIterator; use Iterator; use Symfony\Component\Finder\Finder; use Symfony\Component\Finder\SplFileInfo; /** * A Symfony Finder wrapper which locates files that should go into archives * * Handles .gitignore, .gitattributes and .hgignore files as well as composer's * own exclude rules from composer.json * * @author Nils Adermann <naderman@naderman.de> * @phpstan-extends FilterIterator<string, SplFileInfo, Iterator<string, SplFileInfo>> */ class ArchivableFilesFinder extends FilterIterator { /** * @var Finder */ protected $finder; /** * Initializes the internal Symfony Finder with appropriate filters * * @param string $sources Path to source files to be archived * @param string[] $excludes Composer's own exclude rules from composer.json * @param bool $ignoreFilters Ignore filters when looking for files */ public function __construct(string $sources, array $excludes, bool $ignoreFilters = false) { $fs = new Filesystem(); $sourcesRealPath = realpath($sources); if ($sourcesRealPath === false) { throw new \RuntimeException('Could not realpath() the source directory "'.$sources.'"'); } $sources = $fs->normalizePath($sourcesRealPath); if ($ignoreFilters) { $filters = []; } else { $filters = [ new GitExcludeFilter($sources), new ComposerExcludeFilter($sources, $excludes), ]; } $this->finder = new Finder(); $filter = static function (\SplFileInfo $file) use ($sources, $filters, $fs): bool { $realpath = $file->getRealPath(); if ($realpath === false) { return false; } if ($file->isLink() && strpos($realpath, $sources) !== 0) { return false; } $relativePath = Preg::replace( '#^'.preg_quote($sources, '#').'#', '', $fs->normalizePath($realpath) ); $exclude = false; foreach ($filters as $filter) { $exclude = $filter->filter($relativePath, $exclude); } return !$exclude; }; $this->finder ->in($sources) ->filter($filter) ->ignoreVCS(true) ->ignoreDotFiles(false) ->sortByName(); parent::__construct($this->finder->getIterator()); } public function accept(): bool { /** @var SplFileInfo $current */ $current = $this->getInnerIterator()->current(); if (!$current->isDir()) { return true; } $iterator = new FilesystemIterator((string) $current, FilesystemIterator::SKIP_DOTS); return !$iterator->valid(); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Archiver/BaseExcludeFilter.php
src/Composer/Package/Archiver/BaseExcludeFilter.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; use Symfony\Component\Finder; /** * @author Nils Adermann <naderman@naderman.de> */ abstract class BaseExcludeFilter { /** * @var string */ protected $sourcePath; /** * @var array<array{0: non-empty-string, 1: bool, 2: bool}> array of [$pattern, $negate, $stripLeadingSlash] arrays */ protected $excludePatterns; /** * @param string $sourcePath Directory containing sources to be filtered */ public function __construct(string $sourcePath) { $this->sourcePath = $sourcePath; $this->excludePatterns = []; } /** * Checks the given path against all exclude patterns in this filter * * Negated patterns overwrite exclude decisions of previous filters. * * @param string $relativePath The file's path relative to the sourcePath * @param bool $exclude Whether a previous filter wants to exclude this file * * @return bool Whether the file should be excluded */ public function filter(string $relativePath, bool $exclude): bool { foreach ($this->excludePatterns as $patternData) { [$pattern, $negate, $stripLeadingSlash] = $patternData; if ($stripLeadingSlash) { $path = substr($relativePath, 1); } else { $path = $relativePath; } try { if (Preg::isMatch($pattern, $path)) { $exclude = !$negate; } } catch (\RuntimeException $e) { // suppressed } } return $exclude; } /** * Processes a file containing exclude rules of different formats per line * * @param string[] $lines A set of lines to be parsed * @param callable $lineParser The parser to be used on each line * * @return array<array{0: non-empty-string, 1: bool, 2: bool}> Exclude patterns to be used in filter() */ protected function parseLines(array $lines, callable $lineParser): array { return array_filter( array_map( static function ($line) use ($lineParser) { $line = trim($line); if (!$line || 0 === strpos($line, '#')) { return null; } return $lineParser($line); }, $lines ), static function ($pattern): bool { return $pattern !== null; } ); } /** * Generates a set of exclude patterns for filter() from gitignore rules * * @param string[] $rules A list of exclude rules in gitignore syntax * * @return array<int, array{0: non-empty-string, 1: bool, 2: bool}> Exclude patterns */ protected function generatePatterns(array $rules): array { $patterns = []; foreach ($rules as $rule) { $patterns[] = $this->generatePattern($rule); } return $patterns; } /** * Generates an exclude pattern for filter() from a gitignore rule * * @param string $rule An exclude rule in gitignore syntax * * @return array{0: non-empty-string, 1: bool, 2: bool} An exclude pattern */ protected function generatePattern(string $rule): array { $negate = false; $pattern = ''; if ($rule !== '' && $rule[0] === '!') { $negate = true; $rule = ltrim($rule, '!'); } $firstSlashPosition = strpos($rule, '/'); if (0 === $firstSlashPosition) { $pattern = '^/'; } elseif (false === $firstSlashPosition || strlen($rule) - 1 === $firstSlashPosition) { $pattern = '/'; } $rule = trim($rule, '/'); // remove delimiters as well as caret (^) and dollar sign ($) from the regex $rule = substr(Finder\Glob::toRegex($rule), 2, -2); return ['{'.$pattern.$rule.'(?=$|/)}', $negate, false]; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false