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/tests/Composer/Test/Fixtures/functional/installed-versions2/plugin-b/PluginB.php
tests/Composer/Test/Fixtures/functional/installed-versions2/plugin-b/PluginB.php
<?php use Composer\Plugin\PluginInterface; use Composer\Composer; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\InstalledVersions; class PluginB implements PluginInterface { public function activate(Composer $composer, IOInterface $io) { fwrite(STDERR, '!!PluginBInit'.JsonFile::encode(InstalledVersions::getInstalledPackages(), 320)."\n"); fwrite(STDERR, '!!PluginA:'.(InstalledVersions::isInstalled('plugin/a') ? InstalledVersions::getVersion('plugin/a') : 'null')."\n"); fwrite(STDERR, '!!PluginB:'.(InstalledVersions::isInstalled('plugin/b') ? InstalledVersions::getVersion('plugin/b') : 'null')."\n"); fwrite(STDERR, '!!Versions:console:'.InstalledVersions::getVersion('symfony/console').';process:'.InstalledVersions::getVersion('symfony/process').';filesystem:'.InstalledVersions::getVersion('symfony/filesystem')."\n"); } public function deactivate(Composer $composer, IOInterface $io) { } public function uninstall(Composer $composer, IOInterface $io) { } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/plugin-a/PluginA.php
tests/Composer/Test/Fixtures/functional/installed-versions2/plugin-a/PluginA.php
<?php use Composer\Plugin\PluginInterface; use Composer\Composer; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\InstalledVersions; class PluginA implements PluginInterface { public function activate(Composer $composer, IOInterface $io) { fwrite(STDERR, '!!PluginAInit'.JsonFile::encode(InstalledVersions::getInstalledPackages(), 320)."\n"); fwrite(STDERR, '!!PluginA:'.(InstalledVersions::isInstalled('plugin/a') ? InstalledVersions::getVersion('plugin/a') : 'null')."\n"); fwrite(STDERR, '!!PluginB:'.(InstalledVersions::isInstalled('plugin/b') ? InstalledVersions::getVersion('plugin/b') : 'null')."\n"); fwrite(STDERR, '!!Versions:console:'.InstalledVersions::getVersion('symfony/console').';process:'.InstalledVersions::getVersion('symfony/process').';filesystem:'.InstalledVersions::getVersion('symfony/filesystem')."\n"); } public function deactivate(Composer $composer, IOInterface $io) { } public function uninstall(Composer $composer, IOInterface $io) { } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/deps-pkg/exec.php
tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/deps-pkg/exec.php
<?php fwrite(STDERR, "regular/dep files autoload initialized\n");
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/autoload.php
tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/autoload.php
<?php // autoload.php @generated by Composer require_once __DIR__ . '/composer/autoload_real.php'; return ComposerAutoloaderInit894a6ddbda1e609774926efb0f5a8fc2::getLoader();
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/evil/pkg/exec.php
tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/evil/pkg/exec.php
<?php fwrite(STDERR, "Evil/pkg executed, this should not happen!\n"); exit(1);
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/InstalledVersions.php
tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/InstalledVersions.php
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer; use Composer\Autoload\ClassLoader; use Composer\Semver\VersionParser; /** * This class is copied in every Composer installed project and available to all * * See also https://getcomposer.org/doc/07-runtime.md#installed-versions * * To require its presence, you can require `composer-runtime-api ^2.0` */ class InstalledVersions { /** * @var mixed[]|null * @psalm-var array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>}|array{}|null */ private static $installed; /** * @var bool|null */ private static $canGetVendors; /** * @var array[] * @psalm-var array<string, array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>}> */ private static $installedByVendor = array(); /** * Returns a list of all package names which are present, either by being installed, replaced or provided * * @return string[] * @psalm-return list<string> */ public static function getInstalledPackages() { $packages = array(); foreach (self::getInstalled() as $installed) { $packages[] = array_keys($installed['versions']); } if (1 === \count($packages)) { return $packages[0]; } return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); } /** * Returns a list of all package names with a specific type e.g. 'library' * * @param string $type * @return string[] * @psalm-return list<string> */ public static function getInstalledPackagesByType($type) { $packagesByType = array(); foreach (self::getInstalled() as $installed) { foreach ($installed['versions'] as $name => $package) { if (isset($package['type']) && $package['type'] === $type) { $packagesByType[] = $name; } } } return $packagesByType; } /** * Checks whether the given package is installed * * This also returns true if the package name is provided or replaced by another package * * @param string $packageName * @param bool $includeDevRequirements * @return bool */ public static function isInstalled($packageName, $includeDevRequirements = true) { foreach (self::getInstalled() as $installed) { if (isset($installed['versions'][$packageName])) { return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']); } } return false; } /** * Checks whether the given package satisfies a version constraint * * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: * * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') * * @param VersionParser $parser Install composer/semver to have access to this class and functionality * @param string $packageName * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package * @return bool */ public static function satisfies(VersionParser $parser, $packageName, $constraint) { $constraint = $parser->parseConstraints($constraint); $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); return $provided->matches($constraint); } /** * Returns a version constraint representing all the range(s) which are installed for a given package * * It is easier to use this via isInstalled() with the $constraint argument if you need to check * whether a given version of a package is installed, and not just whether it exists * * @param string $packageName * @return string Version constraint usable with composer/semver */ public static function getVersionRanges($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } $ranges = array(); if (isset($installed['versions'][$packageName]['pretty_version'])) { $ranges[] = $installed['versions'][$packageName]['pretty_version']; } if (array_key_exists('aliases', $installed['versions'][$packageName])) { $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); } if (array_key_exists('replaced', $installed['versions'][$packageName])) { $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); } if (array_key_exists('provided', $installed['versions'][$packageName])) { $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); } return implode(' || ', $ranges); } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @param string $packageName * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present */ public static function getVersion($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } if (!isset($installed['versions'][$packageName]['version'])) { return null; } return $installed['versions'][$packageName]['version']; } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @param string $packageName * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present */ public static function getPrettyVersion($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } if (!isset($installed['versions'][$packageName]['pretty_version'])) { return null; } return $installed['versions'][$packageName]['pretty_version']; } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @param string $packageName * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference */ public static function getReference($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } if (!isset($installed['versions'][$packageName]['reference'])) { return null; } return $installed['versions'][$packageName]['reference']; } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @param string $packageName * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. */ public static function getInstallPath($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @return array * @psalm-return array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string} */ public static function getRootPackage() { $installed = self::getInstalled(); return $installed[0]['root']; } /** * Returns the raw installed.php data for custom implementations * * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. * @return array[] * @psalm-return array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>} */ public static function getRawData() { @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); if (null === self::$installed) { // only require the installed.php file if this file is loaded from its dumped location, // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 if (substr(__DIR__, -8, 1) !== 'C') { self::$installed = include __DIR__ . '/installed.php'; } else { self::$installed = array(); } } return self::$installed; } /** * Returns the raw data of all installed.php which are currently loaded for custom implementations * * @return array[] * @psalm-return list<array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>}> */ public static function getAllRawData() { return self::getInstalled(); } /** * Lets you reload the static array from another file * * This is only useful for complex integrations in which a project needs to use * this class but then also needs to execute another project's autoloader in process, * and wants to ensure both projects have access to their version of installed.php. * * A typical case would be PHPUnit, where it would need to make sure it reads all * the data it needs from this class, then call reload() with * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure * the project in which it runs can then also use this class safely, without * interference between PHPUnit's dependencies and the project's dependencies. * * @param array[] $data A vendor/composer/installed.php data set * @return void * * @psalm-param array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>} $data */ public static function reload($data) { self::$installed = $data; self::$installedByVendor = array(); } /** * @return array[] * @psalm-return list<array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array<string, array{dev_requirement: bool, pretty_version?: string, version?: string, aliases?: string[], reference?: string, replaced?: string[], provided?: string[], install_path?: string, type?: string}>}> */ private static function getInstalled() { if (null === self::$canGetVendors) { self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); } $installed = array(); if (self::$canGetVendors) { foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { if (isset(self::$installedByVendor[$vendorDir])) { $installed[] = self::$installedByVendor[$vendorDir]; } elseif (is_file($vendorDir.'/composer/installed.php')) { $installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php'; if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { self::$installed = $installed[count($installed) - 1]; } } } } if (null === self::$installed) { // only require the installed.php file if this file is loaded from its dumped location, // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 if (substr(__DIR__, -8, 1) !== 'C') { self::$installed = require __DIR__ . '/installed.php'; } else { self::$installed = array(); } } $installed[] = self::$installed; return $installed; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/autoload_files.php
tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/autoload_files.php
<?php // autoload_files.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( '2962aeb5f454bcdf16ad79a35133cf35' => $vendorDir . '/evil/pkg/exec.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/autoload_real.php
tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/autoload_real.php
<?php // autoload_real.php @generated by Composer class ComposerAutoloaderInit894a6ddbda1e609774926efb0f5a8fc2 { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } /** * @return \Composer\Autoload\ClassLoader */ public static function getLoader() { if (null !== self::$loader) { return self::$loader; } spl_autoload_register(array('ComposerAutoloaderInit894a6ddbda1e609774926efb0f5a8fc2', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(\dirname(__FILE__))); spl_autoload_unregister(array('ComposerAutoloaderInit894a6ddbda1e609774926efb0f5a8fc2', 'loadClassLoader')); $useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded()); if ($useStaticLoader) { require __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInit894a6ddbda1e609774926efb0f5a8fc2::getInitializer($loader)); } else { $map = require __DIR__ . '/autoload_namespaces.php'; foreach ($map as $namespace => $path) { $loader->set($namespace, $path); } $map = require __DIR__ . '/autoload_psr4.php'; foreach ($map as $namespace => $path) { $loader->setPsr4($namespace, $path); } $classMap = require __DIR__ . '/autoload_classmap.php'; if ($classMap) { $loader->addClassMap($classMap); } } $loader->register(true); if ($useStaticLoader) { $includeFiles = Composer\Autoload\ComposerStaticInit894a6ddbda1e609774926efb0f5a8fc2::$files; } else { $includeFiles = require __DIR__ . '/autoload_files.php'; } foreach ($includeFiles as $fileIdentifier => $file) { composerRequire894a6ddbda1e609774926efb0f5a8fc2($fileIdentifier, $file); } return $loader; } } /** * @param string $fileIdentifier * @param string $file * @return void */ function composerRequire894a6ddbda1e609774926efb0f5a8fc2($fileIdentifier, $file) { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; require $file; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/autoload_namespaces.php
tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/autoload_namespaces.php
<?php // autoload_namespaces.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/autoload_psr4.php
tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/autoload_psr4.php
<?php // autoload_psr4.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/autoload_static.php
tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/autoload_static.php
<?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInit894a6ddbda1e609774926efb0f5a8fc2 { public static $files = array ( '2962aeb5f454bcdf16ad79a35133cf35' => __DIR__ . '/..' . '/evil/pkg/exec.php', ); public static $classMap = array ( 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->classMap = ComposerStaticInit894a6ddbda1e609774926efb0f5a8fc2::$classMap; }, null, ClassLoader::class); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/installed.php
tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/installed.php
<?php return array( 'root' => array( 'pretty_version' => '1.2.3', 'version' => '1.2.3.0', 'type' => 'library', 'install_path' => __DIR__ . '/../../', 'aliases' => array(), 'reference' => NULL, 'name' => 'root/pkg', 'dev' => true, ), 'versions' => array( 'evil/pkg' => array( 'pretty_version' => '1.0.0', 'version' => '1.0.0.0', 'type' => 'library', 'install_path' => __DIR__ . '/../evil/pkg', 'aliases' => array(), 'reference' => 'a95061d7a7e3cf4466381fd1abc504279c95b231', 'dev_requirement' => false, ), 'root/pkg' => array( 'pretty_version' => '1.2.3', 'version' => '1.2.3.0', 'type' => 'library', 'install_path' => __DIR__ . '/../../', 'aliases' => array(), 'reference' => NULL, 'dev_requirement' => false, ), ), );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/ClassLoader.php
tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/ClassLoader.php
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Autoload; /** * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. * * $loader = new \Composer\Autoload\ClassLoader(); * * // register classes with namespaces * $loader->add('Symfony\Component', __DIR__.'/component'); * $loader->add('Symfony', __DIR__.'/framework'); * * // activate the autoloader * $loader->register(); * * // to enable searching the include path (eg. for PEAR packages) * $loader->setUseIncludePath(true); * * In this example, if you try to use a class in the Symfony\Component * namespace or one of its children (Symfony\Component\Console for instance), * the autoloader will first look for the class under the component/ * directory, and it will then fallback to the framework/ directory if not * found before giving up. * * This class is loosely based on the Symfony UniversalClassLoader. * * @author Fabien Potencier <fabien@symfony.com> * @author Jordi Boggiano <j.boggiano@seld.be> * @see https://www.php-fig.org/psr/psr-0/ * @see https://www.php-fig.org/psr/psr-4/ */ class ClassLoader { /** @var ?string */ private $vendorDir; // PSR-4 /** * @var array[] * @psalm-var array<string, array<string, int>> */ private $prefixLengthsPsr4 = array(); /** * @var array[] * @psalm-var array<string, array<int, string>> */ private $prefixDirsPsr4 = array(); /** * @var array[] * @psalm-var array<string, string> */ private $fallbackDirsPsr4 = array(); // PSR-0 /** * @var array[] * @psalm-var array<string, array<string, string[]>> */ private $prefixesPsr0 = array(); /** * @var array[] * @psalm-var array<string, string> */ private $fallbackDirsPsr0 = array(); /** @var bool */ private $useIncludePath = false; /** * @var string[] * @psalm-var array<string, string> */ private $classMap = array(); /** @var bool */ private $classMapAuthoritative = false; /** * @var bool[] * @psalm-var array<string, bool> */ private $missingClasses = array(); /** @var ?string */ private $apcuPrefix; /** * @var self[] */ private static $registeredLoaders = array(); /** * @param ?string $vendorDir */ public function __construct($vendorDir = null) { $this->vendorDir = $vendorDir; } /** * @return string[] */ public function getPrefixes() { if (!empty($this->prefixesPsr0)) { return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); } return array(); } /** * @return array[] * @psalm-return array<string, array<int, string>> */ public function getPrefixesPsr4() { return $this->prefixDirsPsr4; } /** * @return array[] * @psalm-return array<string, string> */ public function getFallbackDirs() { return $this->fallbackDirsPsr0; } /** * @return array[] * @psalm-return array<string, string> */ public function getFallbackDirsPsr4() { return $this->fallbackDirsPsr4; } /** * @return string[] Array of classname => path * @psalm-return array<string, string> */ public function getClassMap() { return $this->classMap; } /** * @param string[] $classMap Class to filename map * @psalm-param array<string, string> $classMap * * @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 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) { if (!$prefix) { if ($prepend) { $this->fallbackDirsPsr0 = array_merge( (array) $paths, $this->fallbackDirsPsr0 ); } else { $this->fallbackDirsPsr0 = array_merge( $this->fallbackDirsPsr0, (array) $paths ); } return; } $first = $prefix[0]; if (!isset($this->prefixesPsr0[$first][$prefix])) { $this->prefixesPsr0[$first][$prefix] = (array) $paths; return; } if ($prepend) { $this->prefixesPsr0[$first][$prefix] = array_merge( (array) $paths, $this->prefixesPsr0[$first][$prefix] ); } else { $this->prefixesPsr0[$first][$prefix] = array_merge( $this->prefixesPsr0[$first][$prefix], (array) $paths ); } } /** * Registers a set of PSR-4 directories for a given namespace, either * appending or prepending to the ones previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' * @param 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) { if (!$prefix) { // Register directories for the root namespace. if ($prepend) { $this->fallbackDirsPsr4 = array_merge( (array) $paths, $this->fallbackDirsPsr4 ); } else { $this->fallbackDirsPsr4 = array_merge( $this->fallbackDirsPsr4, (array) $paths ); } } elseif (!isset($this->prefixDirsPsr4[$prefix])) { // Register directories for a new namespace. $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } elseif ($prepend) { // Prepend directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( (array) $paths, $this->prefixDirsPsr4[$prefix] ); } else { // Append directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( $this->prefixDirsPsr4[$prefix], (array) $paths ); } } /** * Registers a set of PSR-0 directories for a given prefix, * replacing any others previously set for this prefix. * * @param string $prefix The prefix * @param 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 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($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 indexed by their corresponding vendor directories. * * @return 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; } } /** * Scope isolated include. * * Prevents access to $this/self from included files. * * @param string $file * @return void * @private */ function includeFile($file) { include $file; }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/autoload_classmap.php
tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/vendor/composer/autoload_classmap.php
<?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/plugin-b/PluginB.php
tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/plugin-b/PluginB.php
<?php use Composer\Plugin\PluginInterface; use Composer\Composer; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\InstalledVersions; class PluginB implements PluginInterface { public function activate(Composer $composer, IOInterface $io) { fwrite(STDERR, "!!PluginBInit\n"); } public function deactivate(Composer $composer, IOInterface $io) { } public function uninstall(Composer $composer, IOInterface $io) { } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/evil-pkg/exec.php
tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/evil-pkg/exec.php
<?php fwrite(STDERR, "Evil/pkg executed, this should not happen!\n"); exit(1);
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/plugin-a/PluginA.php
tests/Composer/Test/Fixtures/functional/plugin-autoloading-only-loads-dependencies/plugin-a/PluginA.php
<?php use Composer\Plugin\PluginInterface; use Composer\Composer; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\InstalledVersions; class PluginA implements PluginInterface { public function activate(Composer $composer, IOInterface $io) { fwrite(STDERR, "!!PluginAInit\n"); } public function deactivate(Composer $composer, IOInterface $io) { } public function uninstall(Composer $composer, IOInterface $io) { } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions/Hooks.php
tests/Composer/Test/Fixtures/functional/installed-versions/Hooks.php
<?php use Composer\Json\JsonFile; use Composer\InstalledVersions; use Composer\Script\Event; class Hooks { public static function preUpdate(Event $event) { fwrite(STDERR, '!!PreUpdate:'.JsonFile::encode(InstalledVersions::getInstalledPackages(), 320)."\n"); fwrite(STDERR, '!!Versions:console:'.InstalledVersions::getVersion('symfony/console').';process:'.InstalledVersions::getVersion('symfony/process').';filesystem:'.InstalledVersions::getVersion('symfony/filesystem')."\n"); } public static function postUpdate(Event $event) { fwrite(STDERR, '!!PostUpdate:'.JsonFile::encode(InstalledVersions::getInstalledPackages(), 320)."\n"); fwrite(STDERR, '!!Versions:console:'.InstalledVersions::getVersion('symfony/console').';process:'.InstalledVersions::getVersion('symfony/process').';filesystem:'.InstalledVersions::getVersion('symfony/filesystem')."\n"); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions/plugin-b/PluginB.php
tests/Composer/Test/Fixtures/functional/installed-versions/plugin-b/PluginB.php
<?php use Composer\Plugin\PluginInterface; use Composer\Composer; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\InstalledVersions; class PluginB implements PluginInterface { public function activate(Composer $composer, IOInterface $io) { fwrite(STDERR, '!!PluginBInit'.JsonFile::encode(InstalledVersions::getInstalledPackages(), 320)."\n"); fwrite(STDERR, '!!PluginA:'.(InstalledVersions::isInstalled('plugin/a') ? InstalledVersions::getVersion('plugin/a') : 'null')."\n"); fwrite(STDERR, '!!PluginB:'.(InstalledVersions::isInstalled('plugin/b') ? InstalledVersions::getVersion('plugin/b') : 'null')."\n"); fwrite(STDERR, '!!Versions:console:'.InstalledVersions::getVersion('symfony/console').';process:'.InstalledVersions::getVersion('symfony/process').';filesystem:'.InstalledVersions::getVersion('symfony/filesystem')."\n"); } public function deactivate(Composer $composer, IOInterface $io) { } public function uninstall(Composer $composer, IOInterface $io) { } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions/plugin-a/PluginA.php
tests/Composer/Test/Fixtures/functional/installed-versions/plugin-a/PluginA.php
<?php use Composer\Plugin\PluginInterface; use Composer\Composer; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\InstalledVersions; class PluginA implements PluginInterface { public function activate(Composer $composer, IOInterface $io) { fwrite(STDERR, '!!PluginAInit'.JsonFile::encode(InstalledVersions::getInstalledPackages(), 320)."\n"); fwrite(STDERR, '!!PluginA:'.(InstalledVersions::isInstalled('plugin/a') ? InstalledVersions::getVersion('plugin/a') : 'null')."\n"); fwrite(STDERR, '!!PluginB:'.(InstalledVersions::isInstalled('plugin/b') ? InstalledVersions::getVersion('plugin/b') : 'null')."\n"); fwrite(STDERR, '!!Versions:console:'.InstalledVersions::getVersion('symfony/console').';process:'.InstalledVersions::getVersion('symfony/process').';filesystem:'.InstalledVersions::getVersion('symfony/filesystem')."\n"); } public function deactivate(Composer $composer, IOInterface $io) { } public function uninstall(Composer $composer, IOInterface $io) { } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Json/JsonFormatterTest.php
tests/Composer/Test/Json/JsonFormatterTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Json; use Composer\Json\JsonFormatter; use Composer\Test\TestCase; class JsonFormatterTest extends TestCase { /** * Test if \u0119 will get correctly formatted (unescaped) * https://github.com/composer/composer/issues/2613 */ public function testUnicodeWithPrependedSlash(): void { if (!extension_loaded('mbstring')) { $this->markTestSkipped('Test requires the mbstring extension'); } $backslash = chr(92); $data = '"' . $backslash . $backslash . $backslash . 'u0119"'; $expected = '"' . $backslash . $backslash . 'ę"'; /** @phpstan-ignore staticMethod.dynamicCall, staticMethod.deprecatedClass */ self::assertEquals($expected, JsonFormatter::format($data, true, true)); } /** * Surrogate pairs are intentionally skipped and not unescaped * https://github.com/composer/composer/issues/7510 */ public function testUtf16SurrogatePair(): void { if (!extension_loaded('mbstring')) { $this->markTestSkipped('Test requires the mbstring extension'); } $escaped = '"\ud83d\ude00"'; /** @phpstan-ignore staticMethod.dynamicCall, staticMethod.deprecatedClass */ self::assertEquals($escaped, JsonFormatter::format($escaped, true, true)); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Json/ComposerSchemaTest.php
tests/Composer/Test/Json/ComposerSchemaTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Json; use Composer\Json\JsonFile; use JsonSchema\Validator; use Composer\Test\TestCase; /** * @author Rob Bast <rob.bast@gmail.com> */ class ComposerSchemaTest extends TestCase { public function testNamePattern(): void { $expectedError = [ [ 'property' => 'name', 'message' => 'Does not match the regex pattern ^[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9](([_.]|-{1,2})?[a-z0-9]+)*$', 'constraint' => [ 'name' => 'pattern', 'params' => [ 'pattern' => '^[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9](([_.]|-{1,2})?[a-z0-9]+)*$', ], ], ], ]; $json = '{"name": "vendor/-pack__age", "description": "description"}'; self::assertEquals($expectedError, $this->check($json)); $json = '{"name": "Vendor/Package", "description": "description"}'; self::assertEquals($expectedError, $this->check($json)); } public function versionProvider(): array { return [ ['1.0.0', true], ['1.0.2', true], ['1.1.0', true], ['1.0.0-dev', true], ['1.0.0-Alpha', true], ['1.0.0-ALPHA', true], ['1.0.0-alphA', true], ['1.0.0-alpha3', true], ['1.0.0-Alpha3', true], ['1.0.0-ALPHA3', true], ['1.0.0-Beta', true], ['1.0.0-BETA', true], ['1.0.0-betA', true], ['1.0.0-beta232', true], ['1.0.0-Beta232', true], ['1.0.0-BETA232', true], ['10.4.13beta.2', true], ['1.0.0.RC.15-dev', true], ['1.0.0-RC', true], ['v2.0.4-p', true], ['dev-master', true], ['0.2.5.4', true], ['12345678-123456', true], ['20100102-203040-p1', true], ['2010-01-02.5', true], ['0.2.5.4-rc.2', true], ['dev-feature+issue-1', true], ['1.0.0-alpha.3.1+foo/-bar', true], ['00.01.03.04', true], ['041.x-dev', true], ['dev-foo bar', true], ['invalid', false], ['1.0be', false], ['1.0.0-meh', false], ['feature-foo', false], ['1.0 .2', false], ]; } /** * @dataProvider versionProvider */ public function testVersionPattern(string $version, bool $isValid): void { $json = '{"name": "vendor/package", "description": "description", "version": "' . $version . '"}'; if ($isValid) { self::assertTrue($this->check($json)); } else { self::assertEquals([ [ 'property' => 'version', 'message' => 'Does not match the regex pattern ^[vV]?\\d+(?:[.-]\\d+){0,3}[._-]?(?:(?:[sS][tT][aA][bB][lL][eE]|[bB][eE][tT][aA]|[bB]|[rR][cC]|[aA][lL][pP][hH][aA]|[aA]|[pP][aA][tT][cC][hH]|[pP][lL]|[pP])(?:(?:[.-]?\\d+)*)?)?(?:[.-]?[dD][eE][vV]|\\.x-dev)?(?:\\+.*)?$|^dev-.*$', 'constraint' => [ 'name' => 'pattern', 'params' => [ 'pattern' => '^[vV]?\\d+(?:[.-]\\d+){0,3}[._-]?(?:(?:[sS][tT][aA][bB][lL][eE]|[bB][eE][tT][aA]|[bB]|[rR][cC]|[aA][lL][pP][hH][aA]|[aA]|[pP][aA][tT][cC][hH]|[pP][lL]|[pP])(?:(?:[.-]?\\d+)*)?)?(?:[.-]?[dD][eE][vV]|\\.x-dev)?(?:\\+.*)?$|^dev-.*$', ], ], ], ], $this->check($json)); } } public function testOptionalAbandonedProperty(): void { $json = '{"name": "vendor/package", "description": "description", "abandoned": true}'; self::assertTrue($this->check($json)); } public function testRequireTypes(): void { $json = '{"name": "vendor/package", "description": "description", "require": {"a": ["b"]} }'; self::assertEquals([ [ 'property' => 'require.a', 'message' => 'Array value found, but a string is required', 'constraint' => ['name' => 'type', 'params' => ['found' => 'array', 'expected' => 'a string']], ], ], $this->check($json)); } public function testMinimumStabilityValues(): void { $expectedError = [ [ 'property' => 'minimum-stability', 'message' => 'Does not have a value in the enumeration ["dev","alpha","beta","rc","RC","stable"]', 'constraint' => [ 'name' => 'enum', 'params' => [ 'enum' => ['dev', 'alpha', 'beta', 'rc', 'RC', 'stable'], ], ], ], ]; $json = '{ "name": "vendor/package", "description": "generic description", "minimum-stability": "" }'; self::assertEquals($expectedError, $this->check($json), 'empty string'); $json = '{ "name": "vendor/package", "description": "generic description", "minimum-stability": "dummy" }'; self::assertEquals($expectedError, $this->check($json), 'dummy'); $json = '{ "name": "vendor/package", "description": "generic description", "minimum-stability": "devz" }'; self::assertEquals($expectedError, $this->check($json), 'devz'); $json = '{ "name": "vendor/package", "description": "generic description", "minimum-stability": "dev" }'; self::assertTrue($this->check($json), 'dev'); $json = '{ "name": "vendor/package", "description": "generic description", "minimum-stability": "alpha" }'; self::assertTrue($this->check($json), 'alpha'); $json = '{ "name": "vendor/package", "description": "generic description", "minimum-stability": "beta" }'; self::assertTrue($this->check($json), 'beta'); $json = '{ "name": "vendor/package", "description": "generic description", "minimum-stability": "rc" }'; self::assertTrue($this->check($json), 'rc lowercase'); $json = '{ "name": "vendor/package", "description": "generic description", "minimum-stability": "RC" }'; self::assertTrue($this->check($json), 'rc uppercase'); $json = '{ "name": "vendor/package", "description": "generic description", "minimum-stability": "stable" }'; self::assertTrue($this->check($json), 'stable'); } public function assertAmbiguousRepositoryNotPossible(): void { $json = '{ "repositories": { "foo": { "name": "bar", "type": "path", "url": "vendor/package" } } }'; self::assertFalse($this->check($json)); $json = '{ "repositories": { "foo": { "type": "path", "url": "vendor/package" } } }'; self::assertTrue($this->check($json)); $json = '{ "repositories": [ { "name": "foo", "type": "path", "url": "vendor/package" } ] }'; self::assertTrue($this->check($json)); $json = '{ "repositories": [ { "type": "path", "url": "vendor/package" } ] }'; self::assertTrue($this->check($json)); } /** * @return mixed */ private function check(string $json) { $validator = new Validator(); $json = json_decode($json); $validator->validate($json, (object) ['$ref' => 'file://' . JsonFile::COMPOSER_SCHEMA_PATH]); if (!$validator->isValid()) { $errors = $validator->getErrors(); // remove justinrainbow/json-schema 3.0/5.2 props so it works with all versions foreach ($errors as &$err) { unset($err['pointer'], $err['context']); } return $errors; } return true; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Json/JsonManipulatorTest.php
tests/Composer/Test/Json/JsonManipulatorTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Json; use Composer\Json\JsonFile; use Composer\Json\JsonManipulator; use Composer\Test\TestCase; class JsonManipulatorTest extends TestCase { /** * @dataProvider linkProvider */ public function testAddLink(string $json, string $type, string $package, string $constraint, string $expected): void { $manipulator = new JsonManipulator($json); self::assertTrue($manipulator->addLink($type, $package, $constraint)); self::assertEquals($expected, $manipulator->getContents()); } public static function linkProvider(): array { return [ [ '{}', 'require', 'vendor/baz', 'qux', "{\n". " \"require\": {\n". " \"vendor/baz\": \"qux\"\n". " }\n". "}\n", ], [ '{ "foo": "bar" }', 'require', 'vendor/baz', 'qux', '{ "foo": "bar", "require": { "vendor/baz": "qux" } } ', ], [ '{ "require": { } }', 'require', 'vendor/baz', 'qux', '{ "require": { "vendor/baz": "qux" } } ', ], [ '{ "empty": "", "require": { "foo": "bar" } }', 'require', 'vendor/baz', 'qux', '{ "empty": "", "require": { "foo": "bar", "vendor/baz": "qux" } } ', ], [ '{ "require": { "foo": "bar", "vendor/baz": "baz" } }', 'require', 'vendor/baz', 'qux', '{ "require": { "foo": "bar", "vendor/baz": "qux" } } ', ], [ '{ "require": { "foo": "bar", "vendor/baz": "baz" } }', 'require', 'vEnDoR/bAz', 'qux', '{ "require": { "foo": "bar", "vendor/baz": "qux" } } ', ], [ '{ "require": { "foo": "bar", "vendor\/baz": "baz" } }', 'require', 'vendor/baz', 'qux', '{ "require": { "foo": "bar", "vendor/baz": "qux" } } ', ], [ '{ "require": { "foo": "bar", "vendor\/baz": "baz" } }', 'require', 'vEnDoR/bAz', 'qux', '{ "require": { "foo": "bar", "vendor/baz": "qux" } } ', ], [ '{ "require": { "foo": "bar" }, "repositories": [{ "type": "package", "package": { "require": { "foo": "bar" } } }] }', 'require', 'foo', 'qux', '{ "require": { "foo": "qux" }, "repositories": [{ "type": "package", "package": { "require": { "foo": "bar" } } }] } ', ], [ '{ "repositories": [{ "type": "package", "package": { "require": { "foo": "bar" } } }] }', 'require', 'foo', 'qux', '{ "repositories": [{ "type": "package", "package": { "require": { "foo": "bar" } } }], "require": { "foo": "qux" } } ', ], [ '{ "require": { "php": "5.*" } }', 'require-dev', 'foo', 'qux', '{ "require": { "php": "5.*" }, "require-dev": { "foo": "qux" } } ', ], [ '{ "require": { "php": "5.*" }, "require-dev": { "foo": "bar" } }', 'require-dev', 'foo', 'qux', '{ "require": { "php": "5.*" }, "require-dev": { "foo": "qux" } } ', ], [ '{ "repositories": [{ "type": "package", "package": { "bar": "ba[z", "dist": { "url": "http...", "type": "zip" }, "autoload": { "classmap": [ "foo/bar" ] } } }], "require": { "php": "5.*" }, "require-dev": { "foo": "bar" } }', 'require-dev', 'foo', 'qux', '{ "repositories": [{ "type": "package", "package": { "bar": "ba[z", "dist": { "url": "http...", "type": "zip" }, "autoload": { "classmap": [ "foo/bar" ] } } }], "require": { "php": "5.*" }, "require-dev": { "foo": "qux" } } ', ], [ '{ "config": { "cache-files-ttl": 0, "discard-changes": true }, "minimum-stability": "stable", "prefer-stable": false, "provide": { "heroku-sys/cedar": "14.2016.03.22" }, "repositories": [ { "packagist.org": false }, { "type": "package", "package": [ { "type": "metapackage", "name": "anthonymartin/geo-location", "version": "v1.0.0", "require": { "heroku-sys/php": ">=5.3.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "aws/aws-sdk-php", "version": "3.9.4", "require": { "heroku-sys/php": ">=5.5" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "cloudinary/cloudinary_php", "version": "dev-master", "require": { "heroku-sys/ext-curl": "*", "heroku-sys/ext-json": "*", "heroku-sys/php": ">=5.3.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "doctrine/annotations", "version": "v1.2.7", "require": { "heroku-sys/php": ">=5.3.2" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "doctrine/cache", "version": "v1.6.0", "require": { "heroku-sys/php": "~5.5|~7.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "doctrine/collections", "version": "v1.3.0", "require": { "heroku-sys/php": ">=5.3.2" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "doctrine/common", "version": "v2.6.1", "require": { "heroku-sys/php": "~5.5|~7.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "doctrine/inflector", "version": "v1.1.0", "require": { "heroku-sys/php": ">=5.3.2" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "doctrine/lexer", "version": "v1.0.1", "require": { "heroku-sys/php": ">=5.3.2" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "geoip/geoip", "version": "v1.16", "require": [], "replace": [], "provide": [], "conflict": { "heroku-sys/ext-geoip": "*" } }, { "type": "metapackage", "name": "giggsey/libphonenumber-for-php", "version": "7.2.5", "require": { "heroku-sys/ext-mbstring": "*" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "guzzlehttp/guzzle", "version": "5.3.0", "require": { "heroku-sys/php": ">=5.4.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "guzzlehttp/promises", "version": "1.0.3", "require": { "heroku-sys/php": ">=5.5.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "guzzlehttp/psr7", "version": "1.2.3", "require": { "heroku-sys/php": ">=5.4.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "guzzlehttp/ringphp", "version": "1.1.0", "require": { "heroku-sys/php": ">=5.4.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "guzzlehttp/streams", "version": "3.0.0", "require": { "heroku-sys/php": ">=5.4.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "hipchat/hipchat-php", "version": "v1.4", "require": { "heroku-sys/php": ">=5.3.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "kriswallsmith/buzz", "version": "v0.15", "require": { "heroku-sys/php": ">=5.3.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "league/csv", "version": "8.0.0", "require": { "heroku-sys/ext-mbstring": "*", "heroku-sys/php": ">=5.5.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "league/fractal", "version": "0.13.0", "require": { "heroku-sys/php": ">=5.4" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "mashape/unirest-php", "version": "1.2.1", "require": { "heroku-sys/ext-curl": "*", "heroku-sys/ext-json": "*", "heroku-sys/php": ">=5.3.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "mtdowling/jmespath.php", "version": "2.3.0", "require": { "heroku-sys/php": ">=5.4.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "palex/phpstructureddata", "version": "v2.0.1", "require": { "heroku-sys/php": ">=5.3.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "psr/http-message", "version": "1.0", "require": { "heroku-sys/php": ">=5.3.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "react/promise", "version": "v2.2.1", "require": { "heroku-sys/php": ">=5.4.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "rollbar/rollbar", "version": "v0.15.0", "require": { "heroku-sys/ext-curl": "*" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "ronanguilloux/isocodes", "version": "1.2.0", "require": { "heroku-sys/ext-bcmath": "*", "heroku-sys/php": ">=5.4.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "sendgrid/sendgrid", "version": "2.1.1", "require": { "heroku-sys/php": ">=5.3" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "sendgrid/smtpapi", "version": "0.0.1", "require": { "heroku-sys/php": ">=5.3" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "symfony/css-selector", "version": "v2.8.2", "require": { "heroku-sys/php": ">=5.3.9" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "symfony/http-foundation", "version": "v2.8.2", "require": { "heroku-sys/php": ">=5.3.9" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "symfony/polyfill-php54", "version": "v1.1.0", "require": { "heroku-sys/php": ">=5.3.3" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "symfony/polyfill-php55", "version": "v1.1.0", "require": { "heroku-sys/php": ">=5.3.3" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "thepixeldeveloper/sitemap", "version": "3.0.0", "require": { "heroku-sys/php": ">=5.3.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "tijsverkoyen/css-to-inline-styles", "version": "1.5.5", "require": { "heroku-sys/php": ">=5.3.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "yiisoft/yii", "version": "1.1.17", "require": { "heroku-sys/php": ">=5.1.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "composer.json/composer.lock", "version": "dev-597511d6d51b96e4a8afeba2c79982e5", "require": { "heroku-sys/php": "~5.6.0", "heroku-sys/ext-newrelic": "*", "heroku-sys/ext-gd": "*", "heroku-sys/ext-redis": "*" }, "replace": [], "provide": [], "conflict": [] } ] } ], "require": { "composer.json/composer.lock": "dev-597511d6d51b96e4a8afeba2c79982e5", "anthonymartin/geo-location": "v1.0.0", "aws/aws-sdk-php": "3.9.4", "cloudinary/cloudinary_php": "dev-master", "doctrine/annotations": "v1.2.7", "doctrine/cache": "v1.6.0", "doctrine/collections": "v1.3.0", "doctrine/common": "v2.6.1", "doctrine/inflector": "v1.1.0", "doctrine/lexer": "v1.0.1", "geoip/geoip": "v1.16", "giggsey/libphonenumber-for-php": "7.2.5", "guzzlehttp/guzzle": "5.3.0", "guzzlehttp/promises": "1.0.3", "guzzlehttp/psr7": "1.2.3", "guzzlehttp/ringphp": "1.1.0", "guzzlehttp/streams": "3.0.0", "hipchat/hipchat-php": "v1.4", "kriswallsmith/buzz": "v0.15", "league/csv": "8.0.0", "league/fractal": "0.13.0", "mashape/unirest-php": "1.2.1", "mtdowling/jmespath.php": "2.3.0", "palex/phpstructureddata": "v2.0.1", "psr/http-message": "1.0", "react/promise": "v2.2.1", "rollbar/rollbar": "v0.15.0", "ronanguilloux/isocodes": "1.2.0", "sendgrid/sendgrid": "2.1.1", "sendgrid/smtpapi": "0.0.1", "symfony/css-selector": "v2.8.2", "symfony/http-foundation": "v2.8.2", "symfony/polyfill-php54": "v1.1.0", "symfony/polyfill-php55": "v1.1.0", "thepixeldeveloper/sitemap": "3.0.0", "tijsverkoyen/css-to-inline-styles": "1.5.5", "yiisoft/yii": "1.1.17", "heroku-sys/apache": "^2.4.10", "heroku-sys/nginx": "~1.8.0" } }', 'require', 'foo', 'qux', '{ "config": { "cache-files-ttl": 0, "discard-changes": true }, "minimum-stability": "stable", "prefer-stable": false, "provide": { "heroku-sys/cedar": "14.2016.03.22" }, "repositories": [ { "packagist.org": false }, { "type": "package", "package": [ { "type": "metapackage", "name": "anthonymartin/geo-location", "version": "v1.0.0", "require": { "heroku-sys/php": ">=5.3.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "aws/aws-sdk-php", "version": "3.9.4", "require": { "heroku-sys/php": ">=5.5" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "cloudinary/cloudinary_php", "version": "dev-master", "require": { "heroku-sys/ext-curl": "*", "heroku-sys/ext-json": "*", "heroku-sys/php": ">=5.3.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "doctrine/annotations", "version": "v1.2.7", "require": { "heroku-sys/php": ">=5.3.2" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "doctrine/cache", "version": "v1.6.0", "require": { "heroku-sys/php": "~5.5|~7.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "doctrine/collections", "version": "v1.3.0", "require": { "heroku-sys/php": ">=5.3.2" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "doctrine/common", "version": "v2.6.1", "require": { "heroku-sys/php": "~5.5|~7.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "doctrine/inflector", "version": "v1.1.0", "require": { "heroku-sys/php": ">=5.3.2" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "doctrine/lexer", "version": "v1.0.1", "require": { "heroku-sys/php": ">=5.3.2" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "geoip/geoip", "version": "v1.16", "require": [], "replace": [], "provide": [], "conflict": { "heroku-sys/ext-geoip": "*" } }, { "type": "metapackage", "name": "giggsey/libphonenumber-for-php", "version": "7.2.5", "require": { "heroku-sys/ext-mbstring": "*" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "guzzlehttp/guzzle", "version": "5.3.0", "require": { "heroku-sys/php": ">=5.4.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "guzzlehttp/promises", "version": "1.0.3", "require": { "heroku-sys/php": ">=5.5.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "guzzlehttp/psr7", "version": "1.2.3", "require": { "heroku-sys/php": ">=5.4.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "guzzlehttp/ringphp", "version": "1.1.0", "require": { "heroku-sys/php": ">=5.4.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "guzzlehttp/streams", "version": "3.0.0", "require": { "heroku-sys/php": ">=5.4.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "hipchat/hipchat-php", "version": "v1.4", "require": { "heroku-sys/php": ">=5.3.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "kriswallsmith/buzz", "version": "v0.15", "require": { "heroku-sys/php": ">=5.3.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "league/csv", "version": "8.0.0", "require": { "heroku-sys/ext-mbstring": "*", "heroku-sys/php": ">=5.5.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "league/fractal", "version": "0.13.0", "require": { "heroku-sys/php": ">=5.4" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "mashape/unirest-php", "version": "1.2.1", "require": { "heroku-sys/ext-curl": "*", "heroku-sys/ext-json": "*", "heroku-sys/php": ">=5.3.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "mtdowling/jmespath.php", "version": "2.3.0", "require": { "heroku-sys/php": ">=5.4.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "palex/phpstructureddata", "version": "v2.0.1", "require": { "heroku-sys/php": ">=5.3.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "psr/http-message", "version": "1.0", "require": { "heroku-sys/php": ">=5.3.0" }, "replace": [], "provide": [], "conflict": [] }, { "type": "metapackage", "name": "react/promise", "version": "v2.2.1", "require": { "heroku-sys/php": ">=5.4.0" },
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
true
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Json/JsonFileTest.php
tests/Composer/Test/Json/JsonFileTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Json; use Seld\JsonLint\ParsingException; use Composer\Json\JsonFile; use Composer\Json\JsonValidationException; use Composer\Test\TestCase; class JsonFileTest extends TestCase { public function testParseErrorDetectExtraComma(): void { $json = '{ "foo": "bar", }'; $this->expectParseException('Parse error on line 2', $json); } public function testParseErrorDetectExtraCommaInArray(): void { $json = '{ "foo": [ "bar", ] }'; $this->expectParseException('Parse error on line 3', $json); } public function testParseErrorDetectUnescapedBackslash(): void { $json = '{ "fo\o": "bar" }'; $this->expectParseException('Parse error on line 1', $json); } public function testParseErrorSkipsEscapedBackslash(): void { $json = '{ "fo\\\\o": "bar" "a": "b" }'; $this->expectParseException('Parse error on line 2', $json); } public function testParseErrorDetectSingleQuotes(): void { if (defined('JSON_PARSER_NOTSTRICT') && version_compare(phpversion('json'), '1.3.9', '<')) { $this->markTestSkipped('jsonc issue, see https://github.com/remicollet/pecl-json-c/issues/23'); } $json = '{ \'foo\': "bar" }'; $this->expectParseException('Parse error on line 1', $json); } public function testParseErrorDetectMissingQuotes(): void { $json = '{ foo: "bar" }'; $this->expectParseException('Parse error on line 1', $json); } public function testParseErrorDetectArrayAsHash(): void { $json = '{ "foo": ["bar": "baz"] }'; $this->expectParseException('Parse error on line 2', $json); } public function testParseErrorDetectMissingComma(): void { $json = '{ "foo": "bar" "bar": "foo" }'; $this->expectParseException('Parse error on line 2', $json); } public function testSchemaValidation(): void { self::expectNotToPerformAssertions(); $json = new JsonFile(__DIR__.'/Fixtures/composer.json'); $json->validateSchema(); $json->validateSchema(JsonFile::LAX_SCHEMA); } public function testSchemaValidationError(): void { $file = $this->createTempFile(); file_put_contents($file, '{ "name": null }'); $json = new JsonFile($file); $expectedMessage = sprintf('"%s" does not match the expected JSON schema', $file); $expectedError = 'name : NULL value found, but a string is required'; try { $json->validateSchema(); $this->fail('Expected exception to be thrown (strict)'); } catch (JsonValidationException $e) { self::assertEquals($expectedMessage, $e->getMessage()); self::assertContains($expectedError, $e->getErrors()); } try { $json->validateSchema(JsonFile::LAX_SCHEMA); $this->fail('Expected exception to be thrown (lax)'); } catch (JsonValidationException $e) { self::assertEquals($expectedMessage, $e->getMessage()); self::assertContains($expectedError, $e->getErrors()); } unlink($file); } public function testSchemaValidationLaxAdditionalProperties(): void { $file = $this->createTempFile(); file_put_contents($file, '{ "name": "vendor/package", "description": "generic description", "foo": "bar" }'); $json = new JsonFile($file); try { $json->validateSchema(); $this->fail('Expected exception to be thrown (strict)'); } catch (JsonValidationException $e) { self::assertEquals(sprintf('"%s" does not match the expected JSON schema', $file), $e->getMessage()); self::assertEquals(['The property foo is not defined and the definition does not allow additional properties'], $e->getErrors()); } $json->validateSchema(JsonFile::LAX_SCHEMA); unlink($file); } public function testSchemaValidationLaxRequired(): void { $file = $this->createTempFile(); $json = new JsonFile($file); $expectedMessage = sprintf('"%s" does not match the expected JSON schema', $file); file_put_contents($file, '{ }'); try { $json->validateSchema(); $this->fail('Expected exception to be thrown (strict)'); } catch (JsonValidationException $e) { self::assertEquals($expectedMessage, $e->getMessage()); $errors = $e->getErrors(); self::assertContains('name : The property name is required', $errors); self::assertContains('description : The property description is required', $errors); } $json->validateSchema(JsonFile::LAX_SCHEMA); file_put_contents($file, '{ "name": "vendor/package" }'); try { $json->validateSchema(); $this->fail('Expected exception to be thrown (strict)'); } catch (JsonValidationException $e) { self::assertEquals($expectedMessage, $e->getMessage()); self::assertEquals(['description : The property description is required'], $e->getErrors()); } $json->validateSchema(JsonFile::LAX_SCHEMA); file_put_contents($file, '{ "description": "generic description" }'); try { $json->validateSchema(); $this->fail('Expected exception to be thrown (strict)'); } catch (JsonValidationException $e) { self::assertEquals($expectedMessage, $e->getMessage()); self::assertEquals(['name : The property name is required'], $e->getErrors()); } $json->validateSchema(JsonFile::LAX_SCHEMA); file_put_contents($file, '{ "type": "library" }'); try { $json->validateSchema(); $this->fail('Expected exception to be thrown (strict)'); } catch (JsonValidationException $e) { self::assertEquals($expectedMessage, $e->getMessage()); $errors = $e->getErrors(); self::assertContains('name : The property name is required', $errors); self::assertContains('description : The property description is required', $errors); } $json->validateSchema(JsonFile::LAX_SCHEMA); file_put_contents($file, '{ "type": "project" }'); try { $json->validateSchema(); $this->fail('Expected exception to be thrown (strict)'); } catch (JsonValidationException $e) { self::assertEquals($expectedMessage, $e->getMessage()); $errors = $e->getErrors(); self::assertContains('name : The property name is required', $errors); self::assertContains('description : The property description is required', $errors); } $json->validateSchema(JsonFile::LAX_SCHEMA); file_put_contents($file, '{ "name": "vendor/package", "description": "generic description" }'); $json->validateSchema(); $json->validateSchema(JsonFile::LAX_SCHEMA); unlink($file); } public function testCustomSchemaValidationLax(): void { self::expectNotToPerformAssertions(); $file = $this->createTempFile(); file_put_contents($file, '{ "custom": "property", "another custom": "property" }'); $schema = $this->createTempFile(); file_put_contents($schema, '{ "properties": { "custom": { "type": "string" }}}'); $json = new JsonFile($file); $json->validateSchema(JsonFile::LAX_SCHEMA, $schema); unlink($file); unlink($schema); } public function testCustomSchemaValidationStrict(): void { self::expectNotToPerformAssertions(); $file = $this->createTempFile(); file_put_contents($file, '{ "custom": "property" }'); $schema = $this->createTempFile(); file_put_contents($schema, '{ "properties": { "custom": { "type": "string" }}}'); $json = new JsonFile($file); $json->validateSchema(JsonFile::STRICT_SCHEMA, $schema); unlink($file); unlink($schema); } public function testAuthSchemaValidationWithCustomDataSource(): void { $json = json_decode('{"github-oauth": "foo"}'); $expectedMessage = sprintf('"COMPOSER_AUTH" does not match the expected JSON schema'); $expectedError = 'github-oauth : String value found, but an object is required'; try { JsonFile::validateJsonSchema('COMPOSER_AUTH', $json, JsonFile::AUTH_SCHEMA); $this->fail('Expected exception to be thrown'); } catch (JsonValidationException $e) { self::assertEquals($expectedMessage, $e->getMessage()); self::assertSame([$expectedError], $e->getErrors()); } } public function testParseErrorDetectMissingCommaMultiline(): void { $json = '{ "foo": "barbar" "bar": "foo" }'; $this->expectParseException('Parse error on line 2', $json); } public function testParseErrorDetectMissingColon(): void { $json = '{ "foo": "bar", "bar" "foo" }'; $this->expectParseException('Parse error on line 3', $json); } public function testSimpleJsonString(): void { $data = ['name' => 'composer/composer']; $json = '{ "name": "composer/composer" }'; self::assertJsonFormat($json, $data); } public function testTrailingBackslash(): void { $data = ['Metadata\\' => 'src/']; $json = '{ "Metadata\\\\": "src/" }'; self::assertJsonFormat($json, $data); } public function testFormatEmptyArray(): void { $data = ['test' => [], 'test2' => new \stdClass]; $json = '{ "test": [], "test2": {} }'; self::assertJsonFormat($json, $data); } public function testEscape(): void { $data = ["Metadata\\\"" => 'src/']; $json = '{ "Metadata\\\\\\"": "src/" }'; self::assertJsonFormat($json, $data); } public function testUnicode(): void { $data = ["Žluťoučký \" kůň" => "úpěl ďábelské ódy za €"]; $json = '{ "Žluťoučký \" kůň": "úpěl ďábelské ódy za €" }'; self::assertJsonFormat($json, $data); } public function testOnlyUnicode(): void { $data = "\\/ƌ"; self::assertJsonFormat('"\\\\\\/ƌ"', $data, JSON_UNESCAPED_UNICODE); } public function testEscapedSlashes(): void { $data = "\\/foo"; self::assertJsonFormat('"\\\\\\/foo"', $data, 0); } public function testEscapedBackslashes(): void { $data = "a\\b"; self::assertJsonFormat('"a\\\\b"', $data, 0); } public function testEscapedUnicode(): void { $data = "ƌ"; self::assertJsonFormat('"\\u018c"', $data, 0); } public function testDoubleEscapedUnicode(): void { $jsonFile = new JsonFile('composer.json'); $data = ["Zdjęcia","hjkjhl\\u0119kkjk"]; $encodedData = $jsonFile->encode($data); $doubleEncodedData = $jsonFile->encode(['t' => $encodedData]); $decodedData = json_decode($doubleEncodedData, true); $doubleData = json_decode($decodedData['t'], true); self::assertEquals($data, $doubleData); } public function testPreserveIndentationAfterRead(): void { copy(__DIR__.'/Fixtures/tabs.json', __DIR__.'/Fixtures/tabs2.json'); $jsonFile = new JsonFile(__DIR__.'/Fixtures/tabs2.json'); $data = $jsonFile->read(); $jsonFile->write(['foo' => 'baz']); self::assertSame("{\n\t\"foo\": \"baz\"\n}\n", file_get_contents(__DIR__.'/Fixtures/tabs2.json')); unlink(__DIR__.'/Fixtures/tabs2.json'); } public function testOverwritesIndentationByDefault(): void { copy(__DIR__.'/Fixtures/tabs.json', __DIR__.'/Fixtures/tabs2.json'); $jsonFile = new JsonFile(__DIR__.'/Fixtures/tabs2.json'); $jsonFile->write(['foo' => 'baz']); self::assertSame("{\n \"foo\": \"baz\"\n}\n", file_get_contents(__DIR__.'/Fixtures/tabs2.json')); unlink(__DIR__.'/Fixtures/tabs2.json'); } public function testComposerLockFileMergeConflictSimple(): void { $data = [ '_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 @generated automatically', ], 'content-hash' => 'VCS merge conflict detected. Please run `composer update --lock`.', 'packages' => [], 'packages-dev' => [], 'aliases' => [], 'minimum-stability' => "stable", 'stability-flags' => [], 'prefer-stable' => false, 'prefer-lowest' => false, 'platform' => [], 'platform-dev' => [], 'plugin-api-version' => '2.3.0', ]; $json = (string) file_get_contents(__DIR__ . '/Fixtures/composer-lock-merge-conflict-simple.txt'); $this->assertEquals($data, JsonFile::parseJson($json, '/path/to/composer.lock')); } public function testComposerLockFileMergeConflictSimpleCRLF(): void { $data = [ '_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 @generated automatically', ], 'content-hash' => 'VCS merge conflict detected. Please run `composer update --lock`.', 'packages' => [], 'packages-dev' => [], 'aliases' => [], 'minimum-stability' => "stable", 'stability-flags' => [], 'prefer-stable' => false, 'prefer-lowest' => false, 'platform' => [], 'platform-dev' => [], 'plugin-api-version' => '2.3.0', ]; $json = (string) file_get_contents(__DIR__ . '/Fixtures/composer-lock-merge-conflict-simple.txt'); $this->assertEquals($data, JsonFile::parseJson($json, '/path/to/composer.lock')); } public function testComposerLockFileMergeConflictComplex(): void { // complex files have multiple conflict markers and can thus not be simply resolved $data = (string) file_get_contents(__DIR__ . '/Fixtures/composer-lock-merge-conflict-complex.txt'); $this->expectException(ParsingException::class); // We don't care here what the error message says, just that there is an exception thrown. // Other tests verify that the message text is sensible. JsonFile::parseJson($data, '/path/to/composer.lock'); } public function testComposerLockFileMergeConflictComplexCRLF(): void { // complex files have multiple conflict markers and can thus not be simply resolved $data = (string) file_get_contents(__DIR__ . '/Fixtures/composer-lock-merge-conflict-complex-crlf.txt'); $this->expectException(ParsingException::class); // We don't care here what the error message says, just that there is an exception thrown. // Other tests verify that the message text is sensible. JsonFile::parseJson($data, '/path/to/composer.lock'); } public function testComposerLockFileMergeConflictExtended(): void { $data = (string) file_get_contents(__DIR__ . '/Fixtures/composer-lock-merge-conflict-extended.txt'); $json = JsonFile::parseJson($data, '/path/to/composer.lock'); self::assertSame('VCS merge conflict detected. Please run `composer update --lock`.', $json['content-hash']); } private function expectParseException(string $text, string $json): void { try { $result = JsonFile::parseJson($json); $this->fail(sprintf("Parsing should have failed but didn't.\nExpected:\n\"%s\"\nFor:\n\"%s\"\nGot:\n\"%s\"", $text, $json, var_export($result, true))); } catch (ParsingException $e) { self::assertStringContainsString($text, $e->getMessage()); } } /** * @param mixed $data */ private function assertJsonFormat(string $json, $data, ?int $options = null): void { $file = new JsonFile('composer.json'); $json = str_replace("\r", '', $json); if (null === $options) { self::assertEquals($json, $file->encode($data)); } else { self::assertEquals($json, $file->encode($data, $options)); } } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Json/JsonValidationExceptionTest.php
tests/Composer/Test/Json/JsonValidationExceptionTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Json; use Composer\Json\JsonValidationException; use Composer\Test\TestCase; class JsonValidationExceptionTest extends TestCase { /** * @dataProvider errorProvider * @param string[] $errors * @param string[] $expectedErrors */ public function testGetErrors(string $message, array $errors, string $expectedMessage, array $expectedErrors): void { $object = new JsonValidationException($message, $errors); self::assertSame($expectedMessage, $object->getMessage()); self::assertSame($expectedErrors, $object->getErrors()); } public function testGetErrorsWhenNoErrorsProvided(): void { $object = new JsonValidationException('test message'); self::assertEquals([], $object->getErrors()); } public static function errorProvider(): array { return [ ['test message', [], 'test message', []], ['', ['foo'], '', ['foo']], ]; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Question/StrictConfirmationQuestionTest.php
tests/Composer/Test/Question/StrictConfirmationQuestionTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Question; use Composer\Question\StrictConfirmationQuestion; use Composer\Test\TestCase; use Symfony\Component\Console\Helper\QuestionHelper; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\StreamOutput; /** * based on Symfony\Component\Console\Tests\Helper\QuestionHelperTest * * @author Theo Tonge <theo@theotonge.co.uk> */ class StrictConfirmationQuestionTest extends TestCase { /** * @return string[][] * * @phpstan-return list<array{non-empty-string}> */ public static function getAskConfirmationBadData(): array { return [ ['not correct'], ['no more'], ['yes please'], ['yellow'], ]; } /** * @dataProvider getAskConfirmationBadData */ public function testAskConfirmationBadAnswer(string $answer): void { [$input, $dialog] = $this->createInput($answer."\n"); self::expectException('InvalidArgumentException'); self::expectExceptionMessage('Please answer yes, y, no, or n.'); $question = new StrictConfirmationQuestion('Do you like French fries?'); $question->setMaxAttempts(1); $dialog->ask($input, $this->createOutputInterface(), $question); } /** * @dataProvider getAskConfirmationData */ public function testAskConfirmation(string $question, bool $expected, bool $default = true): void { [$input, $dialog] = $this->createInput($question."\n"); $question = new StrictConfirmationQuestion('Do you like French fries?', $default); self::assertEquals($expected, $dialog->ask($input, $this->createOutputInterface(), $question), 'confirmation question should '.($expected ? 'pass' : 'cancel')); } /** * @return mixed[][] * * @phpstan-return list<array{string, bool}>|list<array{string, bool, bool}> */ public static function getAskConfirmationData(): array { return [ ['', true], ['', false, false], ['y', true], ['yes', true], ['n', false], ['no', false], ]; } public function testAskConfirmationWithCustomTrueAndFalseAnswer(): void { $question = new StrictConfirmationQuestion('Do you like French fries?', false, '/^ja$/i', '/^nein$/i'); [$input, $dialog] = $this->createInput("ja\n"); self::assertTrue($dialog->ask($input, $this->createOutputInterface(), $question)); [$input, $dialog] = $this->createInput("nein\n"); self::assertFalse($dialog->ask($input, $this->createOutputInterface(), $question)); } /** * @return resource */ protected function getInputStream(string $input) { $stream = fopen('php://memory', 'r+', false); self::assertNotFalse($stream); fwrite($stream, $input); rewind($stream); return $stream; } protected function createOutputInterface(): StreamOutput { return new StreamOutput(fopen('php://memory', 'r+', false)); } /** * @return object[] * * @phpstan-return array{ArrayInput, QuestionHelper} */ protected function createInput(string $entry): array { $input = new ArrayInput(['--no-interaction']); $input->setStream($this->getInputStream($entry)); $dialog = new QuestionHelper(); return [$input, $dialog]; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/AutoloadGeneratorTest.php
tests/Composer/Test/Autoload/AutoloadGeneratorTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Autoload; use Composer\Autoload\AutoloadGenerator; use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterFactory; use Composer\IO\BufferIO; use Composer\Package\CompletePackage; use Composer\Package\Link; use Composer\Package\Version\VersionParser; use Composer\Semver\Constraint\Constraint; use Composer\Semver\Constraint\MatchAllConstraint; use Composer\Util\Filesystem; use Composer\Package\AliasPackage; use Composer\Package\Package; use Composer\Package\RootPackage; use Composer\Test\TestCase; use Composer\Script\ScriptEvents; use Composer\Repository\InstalledRepositoryInterface; use Composer\Installer\InstallationManager; use Composer\Config; use Composer\EventDispatcher\EventDispatcher; use Composer\Util\Platform; use PHPUnit\Framework\MockObject\MockObject; class AutoloadGeneratorTest extends TestCase { /** * @var string */ public $vendorDir; /** * @var Config|MockObject */ private $config; /** * @var string */ private $workingDir; /** * @var string */ private $origDir; /** * @var InstallationManager&MockObject */ private $im; /** * @var InstalledRepositoryInterface&MockObject */ private $repository; /** * @var AutoloadGenerator */ private $generator; /** * @var Filesystem */ private $fs; /** * @var BufferIO */ private $io; /** * @var EventDispatcher&MockObject */ private $eventDispatcher; /** * Map of setting name => return value configuration for the stub Config * object. * * @var array<string, callable|bool> */ private $configValueMap; protected function setUp(): void { $this->fs = new Filesystem; $this->workingDir = self::getUniqueTmpDirectory(); $this->vendorDir = $this->workingDir.DIRECTORY_SEPARATOR.'composer-test-autoload'; $this->ensureDirectoryExistsAndClear($this->vendorDir); $this->config = $this->getMockBuilder('Composer\Config')->getMock(); $this->configValueMap = [ 'vendor-dir' => function (): string { return $this->vendorDir; }, 'platform-check' => static function (): bool { return true; }, 'use-include-path' => static function (): bool { return false; }, ]; $this->io = new BufferIO(); $this->config->expects($this->atLeastOnce()) ->method('get') ->will($this->returnCallback(function ($arg) { $ret = null; if (isset($this->configValueMap[$arg])) { $ret = $this->configValueMap[$arg]; if (is_callable($ret)) { $ret = $ret(); } } return $ret; })); $this->origDir = Platform::getCwd(); chdir($this->workingDir); $this->im = $this->getMockBuilder('Composer\Installer\InstallationManager') ->disableOriginalConstructor() ->getMock(); $this->im->expects($this->any()) ->method('getInstallPath') ->will($this->returnCallback(function ($package): ?string { if ($package->getType() === 'metapackage') { return null; } $targetDir = $package->getTargetDir(); return $this->vendorDir.'/'.$package->getName() . ($targetDir ? '/'.$targetDir : ''); })); $this->repository = $this->getMockBuilder('Composer\Repository\InstalledRepositoryInterface')->getMock(); $this->repository->expects($this->any()) ->method('getDevPackageNames') ->willReturn([]); $this->eventDispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher') ->disableOriginalConstructor() ->getMock(); $this->generator = new AutoloadGenerator($this->eventDispatcher, $this->io); } protected function tearDown(): void { parent::tearDown(); chdir($this->origDir); if (is_dir($this->workingDir)) { $this->fs->removeDirectory($this->workingDir); } if (is_dir($this->vendorDir)) { $this->fs->removeDirectory($this->vendorDir); } } public function testRootPackageAutoloading(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload([ 'psr-0' => [ 'Main' => 'src/', 'Lala' => ['src/', 'lib/'], ], 'psr-4' => [ 'Acme\Fruit\\' => 'src-fruit/', 'Acme\Cake\\' => ['src-cake/', 'lib-cake/'], ], 'classmap' => ['composersrc/'], ]); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue([])); $this->fs->ensureDirectoryExists($this->workingDir.'/composer'); $this->fs->ensureDirectoryExists($this->workingDir.'/src/Lala/Test'); $this->fs->ensureDirectoryExists($this->workingDir.'/lib'); file_put_contents($this->workingDir.'/src/Lala/ClassMapMain.php', '<?php namespace Lala; class ClassMapMain {}'); file_put_contents($this->workingDir.'/src/Lala/Test/ClassMapMainTest.php', '<?php namespace Lala\Test; class ClassMapMainTest {}'); $this->fs->ensureDirectoryExists($this->workingDir.'/src-fruit'); $this->fs->ensureDirectoryExists($this->workingDir.'/src-cake'); $this->fs->ensureDirectoryExists($this->workingDir.'/lib-cake'); file_put_contents($this->workingDir.'/src-cake/ClassMapBar.php', '<?php namespace Acme\Cake; class ClassMapBar {}'); $this->fs->ensureDirectoryExists($this->workingDir.'/composersrc'); file_put_contents($this->workingDir.'/composersrc/foo.php', '<?php class ClassMapFoo {}'); $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', true, '_1'); // Assert that autoload_namespaces.php was correctly generated. self::assertAutoloadFiles('main', $this->vendorDir.'/composer'); // Assert that autoload_psr4.php was correctly generated. self::assertAutoloadFiles('psr4', $this->vendorDir.'/composer', 'psr4'); // Assert that autoload_classmap.php was correctly generated. self::assertAutoloadFiles('classmap', $this->vendorDir.'/composer', 'classmap'); } public function testRootPackageDevAutoloading(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload([ 'psr-0' => [ 'Main' => 'src/', ], ]); $package->setDevAutoload([ 'files' => ['devfiles/foo.php'], 'psr-0' => [ 'Main' => 'tests/', ], ]); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue([])); $this->fs->ensureDirectoryExists($this->workingDir.'/composer'); $this->fs->ensureDirectoryExists($this->workingDir.'/src/Main'); file_put_contents($this->workingDir.'/src/Main/ClassMain.php', '<?php namespace Main; class ClassMain {}'); $this->fs->ensureDirectoryExists($this->workingDir.'/devfiles'); file_put_contents($this->workingDir.'/devfiles/foo.php', '<?php function foo() { echo "foo"; }'); // generate autoload files with the dev mode set to true $this->generator->setDevMode(true); $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', true, '_1'); // check standard autoload self::assertAutoloadFiles('main5', $this->vendorDir.'/composer'); self::assertAutoloadFiles('classmap7', $this->vendorDir.'/composer', 'classmap'); // make sure dev autoload is correctly dumped self::assertAutoloadFiles('files2', $this->vendorDir.'/composer', 'files'); } public function testRootPackageDevAutoloadingDisabledByDefault(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload([ 'psr-0' => [ 'Main' => 'src/', ], ]); $package->setDevAutoload([ 'files' => ['devfiles/foo.php'], ]); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue([])); $this->fs->ensureDirectoryExists($this->workingDir.'/composer'); $this->fs->ensureDirectoryExists($this->workingDir.'/src/Main'); file_put_contents($this->workingDir.'/src/Main/ClassMain.php', '<?php namespace Main; class ClassMain {}'); $this->fs->ensureDirectoryExists($this->workingDir.'/devfiles'); file_put_contents($this->workingDir.'/devfiles/foo.php', '<?php function foo() { echo "foo"; }'); $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', true, '_1'); // check standard autoload self::assertAutoloadFiles('main4', $this->vendorDir.'/composer'); self::assertAutoloadFiles('classmap7', $this->vendorDir.'/composer', 'classmap'); // make sure dev autoload is disabled when dev mode is set to false self::assertFalse(is_file($this->vendorDir.'/composer/autoload_files.php')); } public function testVendorDirSameAsWorkingDir(): void { $this->vendorDir = $this->workingDir; $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload([ 'psr-0' => ['Main' => 'src/', 'Lala' => 'src/'], 'psr-4' => [ 'Acme\Fruit\\' => 'src-fruit/', 'Acme\Cake\\' => ['src-cake/', 'lib-cake/'], ], 'classmap' => ['composersrc/'], ]); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue([])); $this->fs->ensureDirectoryExists($this->vendorDir.'/composer'); $this->fs->ensureDirectoryExists($this->vendorDir.'/src/Main'); file_put_contents($this->vendorDir.'/src/Main/Foo.php', '<?php namespace Main; class Foo {}'); $this->fs->ensureDirectoryExists($this->vendorDir.'/composersrc'); file_put_contents($this->vendorDir.'/composersrc/foo.php', '<?php class ClassMapFoo {}'); $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', true, '_2'); self::assertAutoloadFiles('main3', $this->vendorDir.'/composer'); self::assertAutoloadFiles('psr4_3', $this->vendorDir.'/composer', 'psr4'); self::assertAutoloadFiles('classmap3', $this->vendorDir.'/composer', 'classmap'); } public function testRootPackageAutoloadingAlternativeVendorDir(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload([ 'psr-0' => ['Main' => 'src/', 'Lala' => 'src/'], 'psr-4' => [ 'Acme\Fruit\\' => 'src-fruit/', 'Acme\Cake\\' => ['src-cake/', 'lib-cake/'], ], 'classmap' => ['composersrc/'], ]); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue([])); $this->vendorDir .= '/subdir'; $this->fs->ensureDirectoryExists($this->vendorDir.'/composer'); $this->fs->ensureDirectoryExists($this->workingDir.'/src'); $this->fs->ensureDirectoryExists($this->workingDir.'/composersrc'); file_put_contents($this->workingDir.'/composersrc/foo.php', '<?php class ClassMapFoo {}'); $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', false, '_3'); self::assertAutoloadFiles('main2', $this->vendorDir.'/composer'); self::assertAutoloadFiles('psr4_2', $this->vendorDir.'/composer', 'psr4'); self::assertAutoloadFiles('classmap2', $this->vendorDir.'/composer', 'classmap'); } public function testRootPackageAutoloadingWithTargetDir(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload([ 'psr-0' => ['Main\\Foo' => '', 'Main\\Bar' => ''], 'classmap' => ['Main/Foo/src', 'lib'], 'files' => ['foo.php', 'Main/Foo/bar.php'], ]); $package->setTargetDir('Main/Foo/'); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue([])); $this->fs->ensureDirectoryExists($this->vendorDir.'/a'); $this->fs->ensureDirectoryExists($this->workingDir.'/src'); $this->fs->ensureDirectoryExists($this->workingDir.'/lib'); file_put_contents($this->workingDir.'/src/rootfoo.php', '<?php class ClassMapFoo {}'); file_put_contents($this->workingDir.'/lib/rootbar.php', '<?php class ClassMapBar {}'); file_put_contents($this->workingDir.'/foo.php', '<?php class FilesFoo {}'); file_put_contents($this->workingDir.'/bar.php', '<?php class FilesBar {}'); $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', false, 'TargetDir'); self::assertFileContentEquals(__DIR__.'/Fixtures/autoload_target_dir.php', $this->vendorDir.'/autoload.php'); self::assertFileContentEquals(__DIR__.'/Fixtures/autoload_real_target_dir.php', $this->vendorDir.'/composer/autoload_real.php'); self::assertFileContentEquals(__DIR__.'/Fixtures/autoload_static_target_dir.php', $this->vendorDir.'/composer/autoload_static.php'); self::assertFileContentEquals(__DIR__.'/Fixtures/autoload_files_target_dir.php', $this->vendorDir.'/composer/autoload_files.php'); self::assertAutoloadFiles('classmap6', $this->vendorDir.'/composer', 'classmap'); } public function testDuplicateFilesWarning(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload([ 'files' => ['foo.php', 'bar.php', './foo.php', '././foo.php'], ]); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue([])); $this->fs->ensureDirectoryExists($this->vendorDir.'/a'); $this->fs->ensureDirectoryExists($this->workingDir.'/src'); $this->fs->ensureDirectoryExists($this->workingDir.'/lib'); file_put_contents($this->workingDir.'/foo.php', '<?php class FilesFoo {}'); file_put_contents($this->workingDir.'/bar.php', '<?php class FilesBar {}'); $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', false, 'FilesWarning'); self::assertFileContentEquals(__DIR__.'/Fixtures/autoload_files_duplicates.php', $this->vendorDir.'/composer/autoload_files.php'); $expected = '<warning>The following "files" autoload rules are included multiple times, this may cause issues and should be resolved:</warning>'.PHP_EOL. '<warning> - $baseDir . \'/foo.php\'</warning>'.PHP_EOL; self::assertEquals($expected, $this->io->getOutput()); } public function testVendorsAutoloading(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires([ 'a/a' => new Link('a', 'a/a', new MatchAllConstraint()), 'b/b' => new Link('a', 'b/b', new MatchAllConstraint()), ]); $packages = []; $packages[] = $a = new Package('a/a', '1.0', '1.0'); $packages[] = $b = new Package('b/b', '1.0', '1.0'); $packages[] = $c = new AliasPackage($b, '1.2', '1.2'); $a->setAutoload(['psr-0' => ['A' => 'src/', 'A\\B' => 'lib/']]); $b->setAutoload(['psr-0' => ['B\\Sub\\Name' => 'src/']]); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue($packages)); $this->fs->ensureDirectoryExists($this->vendorDir.'/composer'); $this->fs->ensureDirectoryExists($this->vendorDir.'/a/a/src'); $this->fs->ensureDirectoryExists($this->vendorDir.'/a/a/lib'); $this->fs->ensureDirectoryExists($this->vendorDir.'/b/b/src'); $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', false, '_5'); self::assertAutoloadFiles('vendors', $this->vendorDir.'/composer'); self::assertFileExists($this->vendorDir.'/composer/autoload_classmap.php', "ClassMap file needs to be generated, even if empty."); } public function testVendorsAutoloadingWithMetapackages(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires([ 'a/a' => new Link('a', 'a/a', new MatchAllConstraint()), ]); $packages = []; $packages[] = $a = new Package('a/a', '1.0', '1.0'); $packages[] = $b = new Package('b/b', '1.0', '1.0'); $packages[] = $c = new AliasPackage($b, '1.2', '1.2'); $a->setAutoload(['psr-0' => ['A' => 'src/', 'A\\B' => 'lib/']]); $b->setAutoload(['psr-0' => ['B\\Sub\\Name' => 'src/']]); $a->setType('metapackage'); $a->setRequires([ 'b/b' => new Link('a/a', 'b/b', new MatchAllConstraint()), ]); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue($packages)); $this->fs->ensureDirectoryExists($this->vendorDir.'/composer'); $this->fs->ensureDirectoryExists($this->vendorDir.'/b/b/src'); // creating a/a files to make sure they would be found by autoloader even tho they are technically not // needed as the package is a metapackage, but if it fails to be excluded it would find these $this->fs->ensureDirectoryExists($this->vendorDir.'/a/a/src'); $this->fs->ensureDirectoryExists($this->vendorDir.'/a/a/lib'); $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', false, '_5'); self::assertAutoloadFiles('vendors_meta', $this->vendorDir.'/composer'); self::assertFileExists($this->vendorDir.'/composer/autoload_classmap.php', "ClassMap file needs to be generated, even if empty."); } public function testNonDevAutoloadExclusionWithRecursion(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires([ 'a/a' => new Link('a', 'a/a', new MatchAllConstraint()), ]); $packages = []; $packages[] = $a = new Package('a/a', '1.0', '1.0'); $packages[] = $b = new Package('b/b', '1.0', '1.0'); $a->setAutoload(['psr-0' => ['A' => 'src/', 'A\\B' => 'lib/']]); $a->setRequires([ 'b/b' => new Link('a/a', 'b/b', new MatchAllConstraint()), ]); $b->setAutoload(['psr-0' => ['B\\Sub\\Name' => 'src/']]); $b->setRequires([ 'a/a' => new Link('b/b', 'a/a', new MatchAllConstraint()), ]); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue($packages)); $this->fs->ensureDirectoryExists($this->vendorDir.'/composer'); $this->fs->ensureDirectoryExists($this->vendorDir.'/a/a/src'); $this->fs->ensureDirectoryExists($this->vendorDir.'/a/a/lib'); $this->fs->ensureDirectoryExists($this->vendorDir.'/b/b/src'); $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', false, '_5'); self::assertAutoloadFiles('vendors', $this->vendorDir.'/composer'); self::assertFileExists($this->vendorDir.'/composer/autoload_classmap.php', "ClassMap file needs to be generated, even if empty."); } public function testNonDevAutoloadShouldIncludeReplacedPackages(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires(['a/a' => new Link('a', 'a/a', new MatchAllConstraint())]); $packages = []; $packages[] = $a = new Package('a/a', '1.0', '1.0'); $packages[] = $b = new Package('b/b', '1.0', '1.0'); $a->setRequires(['b/c' => new Link('a/a', 'b/c', new MatchAllConstraint())]); $b->setAutoload(['psr-4' => ['B\\' => 'src/']]); $b->setReplaces( ['b/c' => new Link('b/b', 'b/c', new Constraint('==', '1.0'), Link::TYPE_REPLACE)] ); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue($packages)); $this->fs->ensureDirectoryExists($this->vendorDir.'/b/b/src/C'); file_put_contents($this->vendorDir.'/b/b/src/C/C.php', '<?php namespace B\\C; class C {}'); $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', true, '_5'); self::assertEquals( [ 'B\\C\\C' => $this->vendorDir.'/b/b/src/C/C.php', 'Composer\\InstalledVersions' => $this->vendorDir . '/composer/InstalledVersions.php', ], include $this->vendorDir.'/composer/autoload_classmap.php' ); } public function testNonDevAutoloadExclusionWithRecursionReplace(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires([ 'a/a' => new Link('a', 'a/a', new MatchAllConstraint()), ]); $packages = []; $packages[] = $a = new Package('a/a', '1.0', '1.0'); $packages[] = $b = new Package('b/b', '1.0', '1.0'); $a->setAutoload(['psr-0' => ['A' => 'src/', 'A\\B' => 'lib/']]); $a->setRequires([ 'c/c' => new Link('a/a', 'c/c', new MatchAllConstraint()), ]); $b->setAutoload(['psr-0' => ['B\\Sub\\Name' => 'src/']]); $b->setReplaces([ 'c/c' => new Link('b/b', 'c/c', new MatchAllConstraint()), ]); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue($packages)); $this->fs->ensureDirectoryExists($this->vendorDir.'/composer'); $this->fs->ensureDirectoryExists($this->vendorDir.'/a/a/src'); $this->fs->ensureDirectoryExists($this->vendorDir.'/a/a/lib'); $this->fs->ensureDirectoryExists($this->vendorDir.'/b/b/src'); $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', false, '_5'); self::assertAutoloadFiles('vendors', $this->vendorDir.'/composer'); self::assertFileExists($this->vendorDir.'/composer/autoload_classmap.php', "ClassMap file needs to be generated, even if empty."); } public function testNonDevAutoloadReplacesNestedRequirements(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires([ 'a/a' => new Link('a', 'a/a', new MatchAllConstraint()), ]); $packages = []; $packages[] = $a = new Package('a/a', '1.0', '1.0'); $packages[] = $b = new Package('b/b', '1.0', '1.0'); $packages[] = $c = new Package('c/c', '1.0', '1.0'); $packages[] = $d = new Package('d/d', '1.0', '1.0'); $packages[] = $e = new Package('e/e', '1.0', '1.0'); $a->setAutoload(['classmap' => ['src/A.php']]); $a->setRequires([ 'b/b' => new Link('a/a', 'b/b', new MatchAllConstraint()), ]); $b->setAutoload(['classmap' => ['src/B.php']]); $b->setRequires([ 'e/e' => new Link('b/b', 'e/e', new MatchAllConstraint()), ]); $c->setAutoload(['classmap' => ['src/C.php']]); $c->setReplaces([ 'b/b' => new Link('c/c', 'b/b', new MatchAllConstraint()), ]); $c->setRequires([ 'd/d' => new Link('c/c', 'd/d', new MatchAllConstraint()), ]); $d->setAutoload(['classmap' => ['src/D.php']]); $e->setAutoload(['classmap' => ['src/E.php']]); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue($packages)); $this->fs->ensureDirectoryExists($this->vendorDir.'/a/a/src'); $this->fs->ensureDirectoryExists($this->vendorDir.'/b/b/src'); $this->fs->ensureDirectoryExists($this->vendorDir.'/c/c/src'); $this->fs->ensureDirectoryExists($this->vendorDir.'/d/d/src'); $this->fs->ensureDirectoryExists($this->vendorDir.'/e/e/src'); file_put_contents($this->vendorDir.'/a/a/src/A.php', '<?php class A {}'); file_put_contents($this->vendorDir.'/b/b/src/B.php', '<?php class B {}'); file_put_contents($this->vendorDir.'/c/c/src/C.php', '<?php class C {}'); file_put_contents($this->vendorDir.'/d/d/src/D.php', '<?php class D {}'); file_put_contents($this->vendorDir.'/e/e/src/E.php', '<?php class E {}'); $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', false, '_5'); self::assertAutoloadFiles('classmap9', $this->vendorDir.'/composer', 'classmap'); } public function testPharAutoload(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires([ 'a/a' => new Link('a', 'a/a', new MatchAllConstraint()), ]); $package->setAutoload([ 'psr-0' => [ 'Foo' => 'foo.phar', 'Bar' => 'dir/bar.phar/src', ], 'psr-4' => [ 'Baz\\' => 'baz.phar', 'Qux\\' => 'dir/qux.phar/src', ], ]); $vendorPackage = new Package('a/a', '1.0', '1.0'); $vendorPackage->setAutoload([ 'psr-0' => [ 'Lorem' => 'lorem.phar', 'Ipsum' => 'dir/ipsum.phar/src', ], 'psr-4' => [ 'Dolor\\' => 'dolor.phar', 'Sit\\' => 'dir/sit.phar/src', ], ]); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue([$vendorPackage])); $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', true, 'Phar'); self::assertAutoloadFiles('phar', $this->vendorDir . '/composer'); self::assertAutoloadFiles('phar_psr4', $this->vendorDir . '/composer', 'psr4'); self::assertAutoloadFiles('phar_static', $this->vendorDir . '/composer', 'static'); } public function testPSRToClassMapIgnoresNonExistingDir(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload([ 'psr-0' => ['Prefix' => 'foo/bar/non/existing/'], 'psr-4' => ['Prefix\\' => 'foo/bar/non/existing2/'], ]); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue([])); $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', true, '_8'); self::assertFileExists($this->vendorDir.'/composer/autoload_classmap.php', "ClassMap file needs to be generated."); self::assertEquals( [ 'Composer\\InstalledVersions' => $this->vendorDir.'/composer/InstalledVersions.php', ], include $this->vendorDir.'/composer/autoload_classmap.php' ); } public function testPSRToClassMapIgnoresNonPSRClasses(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload([ 'psr-0' => ['psr0_' => 'psr0/'], 'psr-4' => ['psr4\\' => 'psr4/'], ]); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue([])); $this->fs->ensureDirectoryExists($this->workingDir.'/psr0/psr0'); $this->fs->ensureDirectoryExists($this->workingDir.'/psr4'); file_put_contents($this->workingDir.'/psr0/psr0/match.php', '<?php class psr0_match {}'); file_put_contents($this->workingDir.'/psr0/psr0/badfile.php', '<?php class psr0_badclass {}'); file_put_contents($this->workingDir.'/psr4/match.php', '<?php namespace psr4; class match {}'); file_put_contents($this->workingDir.'/psr4/badfile.php', '<?php namespace psr4; class badclass {}'); $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', true, '_1'); self::assertFileExists($this->vendorDir.'/composer/autoload_classmap.php', "ClassMap file needs to be generated."); $expectedClassmap = <<<EOF <?php // autoload_classmap.php @generated by Composer \$vendorDir = dirname(__DIR__); \$baseDir = dirname(\$vendorDir); return array( 'Composer\\\\InstalledVersions' => \$vendorDir . '/composer/InstalledVersions.php', 'psr0_match' => \$baseDir . '/psr0/psr0/match.php', 'psr4\\\\match' => \$baseDir . '/psr4/match.php', ); EOF; self::assertStringEqualsFile($this->vendorDir.'/composer/autoload_classmap.php', $expectedClassmap); } public function testVendorsClassMapAutoloading(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires([ 'a/a' => new Link('a', 'a/a', new MatchAllConstraint()), 'b/b' => new Link('a', 'b/b', new MatchAllConstraint()), ]); $packages = []; $packages[] = $a = new Package('a/a', '1.0', '1.0'); $packages[] = $b = new Package('b/b', '1.0', '1.0'); $a->setAutoload(['classmap' => ['src/']]); $b->setAutoload(['classmap' => ['src/', 'lib/']]); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue($packages)); $this->fs->ensureDirectoryExists($this->vendorDir.'/composer'); $this->fs->ensureDirectoryExists($this->vendorDir.'/a/a/src'); $this->fs->ensureDirectoryExists($this->vendorDir.'/b/b/src'); $this->fs->ensureDirectoryExists($this->vendorDir.'/b/b/lib'); file_put_contents($this->vendorDir.'/a/a/src/a.php', '<?php class ClassMapFoo {}'); file_put_contents($this->vendorDir.'/b/b/src/b.php', '<?php class ClassMapBar {}'); file_put_contents($this->vendorDir.'/b/b/lib/c.php', '<?php class ClassMapBaz {}'); $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', false, '_6'); self::assertFileExists($this->vendorDir.'/composer/autoload_classmap.php', "ClassMap file needs to be generated."); self::assertEquals( [ 'ClassMapBar' => $this->vendorDir.'/b/b/src/b.php', 'ClassMapBaz' => $this->vendorDir.'/b/b/lib/c.php', 'ClassMapFoo' => $this->vendorDir.'/a/a/src/a.php', 'Composer\\InstalledVersions' => $this->vendorDir.'/composer/InstalledVersions.php', ], include $this->vendorDir.'/composer/autoload_classmap.php' ); self::assertAutoloadFiles('classmap4', $this->vendorDir.'/composer', 'classmap'); } public function testVendorsClassMapAutoloadingWithTargetDir(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires([ 'a/a' => new Link('a', 'a/a', new MatchAllConstraint()), 'b/b' => new Link('a', 'b/b', new MatchAllConstraint()), ]); $packages = []; $packages[] = $a = new Package('a/a', '1.0', '1.0'); $packages[] = $b = new Package('b/b', '1.0', '1.0'); $a->setAutoload(['classmap' => ['target/src/', 'lib/']]); $a->setTargetDir('target'); $b->setAutoload(['classmap' => ['src/']]); $this->repository->expects($this->once()) ->method('getCanonicalPackages') ->will($this->returnValue($packages)); $this->fs->ensureDirectoryExists($this->vendorDir.'/composer');
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
true
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/ClassLoaderTest.php
tests/Composer/Test/Autoload/ClassLoaderTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Autoload; use Composer\Autoload\ClassLoader; use Composer\Test\TestCase; /** * Tests the Composer\Autoload\ClassLoader class. */ class ClassLoaderTest extends TestCase { /** * Tests regular PSR-0 and PSR-4 class loading. * * @dataProvider getLoadClassTests * * @param string $class The fully-qualified class name to test, without preceding namespace separator. */ public function testLoadClass(string $class): void { $loader = new ClassLoader(); $loader->add('Namespaced\\', __DIR__ . '/Fixtures'); $loader->add('Pearlike_', __DIR__ . '/Fixtures'); $loader->addPsr4('ShinyVendor\\ShinyPackage\\', __DIR__ . '/Fixtures'); $loader->loadClass($class); self::assertTrue(class_exists($class, false), "->loadClass() loads '$class'"); } /** * Provides arguments for ->testLoadClass(). * * @return array<array<string>> Array of parameter sets to test with. */ public static function getLoadClassTests(): array { return [ ['Namespaced\\Foo'], ['Pearlike_Foo'], ['ShinyVendor\\ShinyPackage\\SubNamespace\\Foo'], ]; } /** * getPrefixes method should return empty array if ClassLoader does not have any psr-0 configuration */ public function testGetPrefixesWithNoPSR0Configuration(): void { $loader = new ClassLoader(); self::assertEmpty($loader->getPrefixes()); } public function testSerializability(): void { $loader = new ClassLoader(); $loader->add('Pearlike_', __DIR__ . '/Fixtures'); $loader->add('', __DIR__ . '/FALLBACK'); $loader->addPsr4('ShinyVendor\\ShinyPackage\\', __DIR__ . '/Fixtures'); $loader->addPsr4('', __DIR__ . '/FALLBACKPSR4'); $loader->addClassMap(['A' => '', 'B' => 'path']); $loader->setApcuPrefix('prefix'); $loader->setClassMapAuthoritative(true); $loader->setUseIncludePath(true); $loader2 = unserialize(serialize($loader)); self::assertInstanceOf(ClassLoader::class, $loader2); self::assertSame($loader->getApcuPrefix(), $loader2->getApcuPrefix()); self::assertSame($loader->getClassMap(), $loader2->getClassMap()); self::assertSame($loader->getFallbackDirs(), $loader2->getFallbackDirs()); self::assertSame($loader->getFallbackDirsPsr4(), $loader2->getFallbackDirsPsr4()); self::assertSame($loader->getPrefixes(), $loader2->getPrefixes()); self::assertSame($loader->getPrefixesPsr4(), $loader2->getPrefixesPsr4()); self::assertSame($loader->getUseIncludePath(), $loader2->getUseIncludePath()); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/MinimumVersionSupport/main.php
tests/Composer/Test/Autoload/MinimumVersionSupport/main.php
<?php include 'vendor/autoload.php'; Test\Foo::test(); if (Composer\InstalledVersions::isInstalled('root/pkg')) { echo 'isInstalled: OK'.PHP_EOL; }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/MinimumVersionSupport/Foo.php
tests/Composer/Test/Autoload/MinimumVersionSupport/Foo.php
<?php namespace Test; class Foo { /** * @return void */ public static function test() { echo 'psr-4 autoloading: OK'.PHP_EOL; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/MinimumVersionSupport/test.php
tests/Composer/Test/Autoload/MinimumVersionSupport/test.php
<?php echo 'files autoloading: OK'.PHP_EOL;
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_phar_static.php
tests/Composer/Test/Autoload/Fixtures/autoload_phar_static.php
<?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInitPhar { public static $prefixLengthsPsr4 = array ( 'S' => array ( 'Sit\\' => 4, ), 'Q' => array ( 'Qux\\' => 4, ), 'D' => array ( 'Dolor\\' => 6, ), 'B' => array ( 'Baz\\' => 4, ), ); public static $prefixDirsPsr4 = array ( 'Sit\\' => array ( 0 => 'phar://' . __DIR__ . '/..' . '/a/a/dir/sit.phar/src', ), 'Qux\\' => array ( 0 => 'phar://' . __DIR__ . '/../..' . '/dir/qux.phar/src', ), 'Dolor\\' => array ( 0 => 'phar://' . __DIR__ . '/..' . '/a/a/dolor.phar', ), 'Baz\\' => array ( 0 => 'phar://' . __DIR__ . '/../..' . '/baz.phar', ), ); public static $prefixesPsr0 = array ( 'L' => array ( 'Lorem' => array ( 0 => 'phar://' . __DIR__ . '/..' . '/a/a/lorem.phar', ), ), 'I' => array ( 'Ipsum' => array ( 0 => 'phar://' . __DIR__ . '/..' . '/a/a/dir/ipsum.phar/src', ), ), 'F' => array ( 'Foo' => array ( 0 => 'phar://' . __DIR__ . '/../..' . '/foo.phar', ), ), 'B' => array ( 'Bar' => array ( 0 => 'phar://' . __DIR__ . '/../..' . '/dir/bar.phar/src', ), ), ); public static $classMap = array ( 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->prefixLengthsPsr4 = ComposerStaticInitPhar::$prefixLengthsPsr4; $loader->prefixDirsPsr4 = ComposerStaticInitPhar::$prefixDirsPsr4; $loader->prefixesPsr0 = ComposerStaticInitPhar::$prefixesPsr0; $loader->classMap = ComposerStaticInitPhar::$classMap; }, null, ClassLoader::class); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_classmap7.php
tests/Composer/Test/Autoload/Fixtures/autoload_classmap7.php
<?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', 'Main\\ClassMain' => $baseDir . '/src/Main/ClassMain.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/include_paths_functions.php
tests/Composer/Test/Autoload/Fixtures/include_paths_functions.php
<?php // include_paths.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( $baseDir . '/lib', $baseDir . '/src', $vendorDir . '/a/a/lib1', $vendorDir . '/a/a/src1', $vendorDir . '/b/b/lib2', $vendorDir . '/c/c/lib3', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_main.php
tests/Composer/Test/Autoload/Fixtures/autoload_main.php
<?php // autoload_namespaces.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'Main' => array($baseDir . '/src'), 'Lala' => array($baseDir . '/src', $baseDir . '/lib'), );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/include_paths_functions_with_removed_extra.php
tests/Composer/Test/Autoload/Fixtures/include_paths_functions_with_removed_extra.php
<?php // include_paths.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( $baseDir . '/lib', $baseDir . '/src', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_static_functions_with_removed_include_paths_and_autolad_files.php
tests/Composer/Test/Autoload/Fixtures/autoload_static_functions_with_removed_include_paths_and_autolad_files.php
<?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInitFilesAutoload { public static $classMap = array ( 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->classMap = ComposerStaticInitFilesAutoload::$classMap; }, null, ClassLoader::class); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_files_functions.php
tests/Composer/Test/Autoload/Fixtures/autoload_files_functions.php
<?php // autoload_files.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( '6d9003eea93a81f3586b5d9c5bd91272' => $vendorDir . '/a/a/test.php', 'e56cac94f86c787e1efd645809df361d' => $vendorDir . '/b/b/test2.php', 'df8470dfa2ebd6b31da05b60fb4ec29a' => $vendorDir . '/c/c/foo/bar/test3.php', '68f1e24e6cd39de885cb5a47678e6518' => $vendorDir . '/c/c/foo/bar/test4.php', '5e70d6595c54512c151823ca0663ab51' => $baseDir . '/root.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_target_dir.php
tests/Composer/Test/Autoload/Fixtures/autoload_target_dir.php
<?php // autoload.php @generated by Composer if (PHP_VERSION_ID < 50600) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } $err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL; if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, $err); } elseif (!headers_sent()) { echo $err; } } throw new RuntimeException($err); } require_once __DIR__ . '/composer/autoload_real.php'; return ComposerAutoloaderInitTargetDir::getLoader();
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_files.php
tests/Composer/Test/Autoload/Fixtures/autoload_files.php
<?php // autoload_files.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( '25b429360a61ca2629fdf9a4f484981c' => $baseDir . '/foo.php', '524f65941cc9a0fa65ff0ec097ccde8a' => $baseDir . '/bar.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_functions_by_dependency.php
tests/Composer/Test/Autoload/Fixtures/autoload_functions_by_dependency.php
<?php // autoload.php @generated by Composer if (PHP_VERSION_ID < 50600) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } $err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL; if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, $err); } elseif (!headers_sent()) { echo $err; } } throw new RuntimeException($err); } require_once __DIR__ . '/composer/autoload_real.php'; return ComposerAutoloaderInitFilesAutoloadOrder::getLoader();
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_phar_psr4.php
tests/Composer/Test/Autoload/Fixtures/autoload_phar_psr4.php
<?php // autoload_psr4.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'Sit\\' => array('phar://' . $vendorDir . '/a/a/dir/sit.phar/src'), 'Qux\\' => array('phar://' . $baseDir . '/dir/qux.phar/src'), 'Dolor\\' => array('phar://' . $vendorDir . '/a/a/dolor.phar'), 'Baz\\' => array('phar://' . $baseDir . '/baz.phar'), );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_static_files_by_dependency.php
tests/Composer/Test/Autoload/Fixtures/autoload_static_files_by_dependency.php
<?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInitFilesAutoloadOrder { public static $files = array ( 'bfdd693009729d60c830ff8d79129635' => __DIR__ . '/..' . '/c/lorem/testC.php', '61e6098c8cafe404d6cf19e59fc2b788' => __DIR__ . '/..' . '/d/d/testD.php', 'c5466e580c6c2403f225c43b6a21a96f' => __DIR__ . '/..' . '/b/bar/testB.php', '69dfc37c40a853a7cbac6c9d2367c5f4' => __DIR__ . '/..' . '/e/e/testE.php', '8bceec6fdc149a1a6acbf7ad3cfed51c' => __DIR__ . '/..' . '/z/foo/testA.php', 'ab280164f4754f5dfdb0721de84d737f' => __DIR__ . '/../..' . '/root2.php', ); public static $classMap = array ( 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->classMap = ComposerStaticInitFilesAutoloadOrder::$classMap; }, null, ClassLoader::class); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_classmap8.php
tests/Composer/Test/Autoload/Fixtures/autoload_classmap8.php
<?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'ClassMapBar' => $vendorDir . '/b/b/ClassMapBar.php', 'ClassMapBaz' => $vendorDir . '/c/c/foo/ClassMapBaz.php', 'ClassMapFoo' => $vendorDir . '/a/a/src/ClassMapFoo.php', 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_classmap2.php
tests/Composer/Test/Autoload/Fixtures/autoload_classmap2.php
<?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname(dirname($vendorDir)); return array( 'ClassMapFoo' => $baseDir . '/composersrc/foo.php', 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_real_files_by_dependency.php
tests/Composer/Test/Autoload/Fixtures/autoload_real_files_by_dependency.php
<?php // autoload_real.php @generated by Composer class ComposerAutoloaderInitFilesAutoloadOrder { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } /** * @return \Composer\Autoload\ClassLoader */ public static function getLoader() { if (null !== self::$loader) { return self::$loader; } spl_autoload_register(array('ComposerAutoloaderInitFilesAutoloadOrder', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__)); spl_autoload_unregister(array('ComposerAutoloaderInitFilesAutoloadOrder', 'loadClassLoader')); require __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInitFilesAutoloadOrder::getInitializer($loader)); $loader->register(true); $filesToLoad = \Composer\Autoload\ComposerStaticInitFilesAutoloadOrder::$files; $requireFile = \Closure::bind(static function ($fileIdentifier, $file) { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; require $file; } }, null, null); foreach ($filesToLoad as $fileIdentifier => $file) { $requireFile($fileIdentifier, $file); } return $loader; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_psr4_3.php
tests/Composer/Test/Autoload/Fixtures/autoload_psr4_3.php
<?php // autoload_psr4.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = $vendorDir; return array( 'Acme\\Fruit\\' => array($vendorDir . '/src-fruit'), 'Acme\\Cake\\' => array($vendorDir . '/src-cake', $vendorDir . '/lib-cake'), );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_phar.php
tests/Composer/Test/Autoload/Fixtures/autoload_phar.php
<?php // autoload_namespaces.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'Lorem' => array('phar://' . $vendorDir . '/a/a/lorem.phar'), 'Ipsum' => array('phar://' . $vendorDir . '/a/a/dir/ipsum.phar/src'), 'Foo' => array('phar://' . $baseDir . '/foo.phar'), 'Bar' => array('phar://' . $baseDir . '/dir/bar.phar/src'), );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_files_functions_with_removed_extra.php
tests/Composer/Test/Autoload/Fixtures/autoload_files_functions_with_removed_extra.php
<?php // autoload_files.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( '5e70d6595c54512c151823ca0663ab51' => $baseDir . '/root.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_real_target_dir.php
tests/Composer/Test/Autoload/Fixtures/autoload_real_target_dir.php
<?php // autoload_real.php @generated by Composer class ComposerAutoloaderInitTargetDir { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } /** * @return \Composer\Autoload\ClassLoader */ public static function getLoader() { if (null !== self::$loader) { return self::$loader; } spl_autoload_register(array('ComposerAutoloaderInitTargetDir', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__)); spl_autoload_unregister(array('ComposerAutoloaderInitTargetDir', 'loadClassLoader')); require __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInitTargetDir::getInitializer($loader)); spl_autoload_register(array('ComposerAutoloaderInitTargetDir', 'autoload'), true, true); $loader->register(true); $filesToLoad = \Composer\Autoload\ComposerStaticInitTargetDir::$files; $requireFile = \Closure::bind(static function ($fileIdentifier, $file) { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; require $file; } }, null, null); foreach ($filesToLoad as $fileIdentifier => $file) { $requireFile($fileIdentifier, $file); } return $loader; } public static function autoload($class) { $dir = dirname(dirname(__DIR__)) . '/'; $prefixes = array('Main\\Foo', 'Main\\Bar'); foreach ($prefixes as $prefix) { if (0 !== strpos($class, $prefix)) { continue; } $path = $dir . implode('/', array_slice(explode('\\', $class), 2)).'.php'; if (!$path = stream_resolve_include_path($path)) { return false; } require $path; return true; } } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_static_functions_with_include_paths.php
tests/Composer/Test/Autoload/Fixtures/autoload_static_functions_with_include_paths.php
<?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInitFilesAutoload { public static $files = array ( '6d9003eea93a81f3586b5d9c5bd91272' => __DIR__ . '/..' . '/a/a/test.php', 'e56cac94f86c787e1efd645809df361d' => __DIR__ . '/..' . '/b/b/test2.php', 'df8470dfa2ebd6b31da05b60fb4ec29a' => __DIR__ . '/..' . '/c/c/foo/bar/test3.php', '68f1e24e6cd39de885cb5a47678e6518' => __DIR__ . '/..' . '/c/c/foo/bar/test4.php', '5e70d6595c54512c151823ca0663ab51' => __DIR__ . '/../..' . '/root.php', ); public static $classMap = array ( 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->classMap = ComposerStaticInitFilesAutoload::$classMap; }, null, ClassLoader::class); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_files_duplicates.php
tests/Composer/Test/Autoload/Fixtures/autoload_files_duplicates.php
<?php // autoload_files.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'b4b4f2eb2151c57cadbd5714a7aba8b7' => $baseDir . '/foo.php', '99b24fc198db06c1d2d8118a8a5475eb' => $baseDir . '/bar.php', '6bad5af0771cca3d076e69b25d0791bb' => $baseDir . '/foo.php', '51841489e2c601aedd3623cb72708483' => $baseDir . '/foo.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_real_functions_with_include_paths.php
tests/Composer/Test/Autoload/Fixtures/autoload_real_functions_with_include_paths.php
<?php // autoload_real.php @generated by Composer class ComposerAutoloaderInitFilesAutoload { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } /** * @return \Composer\Autoload\ClassLoader */ public static function getLoader() { if (null !== self::$loader) { return self::$loader; } spl_autoload_register(array('ComposerAutoloaderInitFilesAutoload', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__)); spl_autoload_unregister(array('ComposerAutoloaderInitFilesAutoload', 'loadClassLoader')); $includePaths = require __DIR__ . '/include_paths.php'; $includePaths[] = get_include_path(); set_include_path(implode(PATH_SEPARATOR, $includePaths)); require __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInitFilesAutoload::getInitializer($loader)); $loader->register(true); $filesToLoad = \Composer\Autoload\ComposerStaticInitFilesAutoload::$files; $requireFile = \Closure::bind(static function ($fileIdentifier, $file) { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; require $file; } }, null, null); foreach ($filesToLoad as $fileIdentifier => $file) { $requireFile($fileIdentifier, $file); } return $loader; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_files2.php
tests/Composer/Test/Autoload/Fixtures/autoload_files2.php
<?php // autoload_files.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'fd1502a3b53705310b21799d025f0dee' => $baseDir . '/devfiles/foo.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_classmap4.php
tests/Composer/Test/Autoload/Fixtures/autoload_classmap4.php
<?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'ClassMapBar' => $vendorDir . '/b/b/src/b.php', 'ClassMapBaz' => $vendorDir . '/b/b/lib/c.php', 'ClassMapFoo' => $vendorDir . '/a/a/src/a.php', 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/include_paths.php
tests/Composer/Test/Autoload/Fixtures/include_paths.php
<?php // include_paths.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( $vendorDir . '/a/a/lib', $vendorDir . '/b/b/library', $vendorDir . '/c/library', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_static_target_dir.php
tests/Composer/Test/Autoload/Fixtures/autoload_static_target_dir.php
<?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInitTargetDir { public static $files = array ( 'b4b4f2eb2151c57cadbd5714a7aba8b7' => __DIR__ . '/../..' . '/foo.php', '99b24fc198db06c1d2d8118a8a5475eb' => __DIR__ . '/../..' . '/bar.php', ); public static $prefixesPsr0 = array ( 'M' => array ( 'Main\\Foo' => array ( 0 => __DIR__ . '/../..' . '/', ), 'Main\\Bar' => array ( 0 => __DIR__ . '/../..' . '/', ), ), ); public static $classMap = array ( 'ClassMapBar' => __DIR__ . '/../..' . '/lib/rootbar.php', 'ClassMapFoo' => __DIR__ . '/../..' . '/src/rootfoo.php', 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->prefixesPsr0 = ComposerStaticInitTargetDir::$prefixesPsr0; $loader->classMap = ComposerStaticInitTargetDir::$classMap; }, null, ClassLoader::class); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_main4.php
tests/Composer/Test/Autoload/Fixtures/autoload_main4.php
<?php // autoload_namespaces.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'Main' => array($baseDir . '/src'), );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_classmap5.php
tests/Composer/Test/Autoload/Fixtures/autoload_classmap5.php
<?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'ClassMapBar' => $vendorDir . '/b/b/test.php', 'ClassMapBaz' => $vendorDir . '/c/c/foo/test.php', 'ClassMapFoo' => $vendorDir . '/a/a/src/a.php', 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_real_include_path.php
tests/Composer/Test/Autoload/Fixtures/autoload_real_include_path.php
<?php // autoload_real.php @generated by Composer class ComposerAutoloaderInitIncludePath { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } /** * @return \Composer\Autoload\ClassLoader */ public static function getLoader() { if (null !== self::$loader) { return self::$loader; } spl_autoload_register(array('ComposerAutoloaderInitIncludePath', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__)); spl_autoload_unregister(array('ComposerAutoloaderInitIncludePath', 'loadClassLoader')); require __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInitIncludePath::getInitializer($loader)); $loader->setUseIncludePath(true); spl_autoload_register(array('ComposerAutoloaderInitIncludePath', 'autoload'), true, true); $loader->register(true); return $loader; } public static function autoload($class) { $dir = dirname(dirname(__DIR__)) . '/'; $prefixes = array('Main\\Foo', 'Main\\Bar'); foreach ($prefixes as $prefix) { if (0 !== strpos($class, $prefix)) { continue; } $path = $dir . implode('/', array_slice(explode('\\', $class), 2)).'.php'; if (!$path = stream_resolve_include_path($path)) { return false; } require $path; return true; } } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_main5.php
tests/Composer/Test/Autoload/Fixtures/autoload_main5.php
<?php // autoload_namespaces.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'Main' => array($baseDir . '/src', $baseDir . '/tests'), );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_classmap9.php
tests/Composer/Test/Autoload/Fixtures/autoload_classmap9.php
<?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'A' => $vendorDir . '/a/a/src/A.php', 'C' => $vendorDir . '/c/c/src/C.php', 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', 'D' => $vendorDir . '/d/d/src/D.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_psr4.php
tests/Composer/Test/Autoload/Fixtures/autoload_psr4.php
<?php // autoload_psr4.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'Acme\\Fruit\\' => array($baseDir . '/src-fruit'), 'Acme\\Cake\\' => array($baseDir . '/src-cake', $baseDir . '/lib-cake'), );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_real_functions.php
tests/Composer/Test/Autoload/Fixtures/autoload_real_functions.php
<?php // autoload_real.php @generated by Composer class ComposerAutoloaderInitFilesAutoload { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } /** * @return \Composer\Autoload\ClassLoader */ public static function getLoader() { if (null !== self::$loader) { return self::$loader; } spl_autoload_register(array('ComposerAutoloaderInitFilesAutoload', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__)); spl_autoload_unregister(array('ComposerAutoloaderInitFilesAutoload', 'loadClassLoader')); require __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInitFilesAutoload::getInitializer($loader)); $loader->register(true); $filesToLoad = \Composer\Autoload\ComposerStaticInitFilesAutoload::$files; $requireFile = \Closure::bind(static function ($fileIdentifier, $file) { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; require $file; } }, null, null); foreach ($filesToLoad as $fileIdentifier => $file) { $requireFile($fileIdentifier, $file); } return $loader; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_vendors.php
tests/Composer/Test/Autoload/Fixtures/autoload_vendors.php
<?php // autoload_namespaces.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'B\\Sub\\Name' => array($vendorDir . '/b/b/src'), 'A\\B' => array($vendorDir . '/a/a/lib'), 'A' => array($vendorDir . '/a/a/src'), );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_main2.php
tests/Composer/Test/Autoload/Fixtures/autoload_main2.php
<?php // autoload_namespaces.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname(dirname($vendorDir)); return array( 'Main' => array($baseDir . '/src'), 'Lala' => array($baseDir . '/src'), );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_files_target_dir.php
tests/Composer/Test/Autoload/Fixtures/autoload_files_target_dir.php
<?php // autoload_files.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'b4b4f2eb2151c57cadbd5714a7aba8b7' => $baseDir . '/foo.php', '99b24fc198db06c1d2d8118a8a5475eb' => $baseDir . '/bar.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_static_functions.php
tests/Composer/Test/Autoload/Fixtures/autoload_static_functions.php
<?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInitFilesAutoload { public static $files = array ( '6d9003eea93a81f3586b5d9c5bd91272' => __DIR__ . '/..' . '/a/a/test.php', 'e56cac94f86c787e1efd645809df361d' => __DIR__ . '/..' . '/b/b/test2.php', 'df8470dfa2ebd6b31da05b60fb4ec29a' => __DIR__ . '/..' . '/c/c/foo/bar/test3.php', '68f1e24e6cd39de885cb5a47678e6518' => __DIR__ . '/..' . '/c/c/foo/bar/test4.php', '5e70d6595c54512c151823ca0663ab51' => __DIR__ . '/../..' . '/root.php', ); public static $classMap = array ( 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->classMap = ComposerStaticInitFilesAutoload::$classMap; }, null, ClassLoader::class); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_classmap3.php
tests/Composer/Test/Autoload/Fixtures/autoload_classmap3.php
<?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = $vendorDir; return array( 'ClassMapFoo' => $vendorDir . '/composersrc/foo.php', 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', 'Main\\Foo' => $vendorDir . '/src/Main/Foo.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_functions.php
tests/Composer/Test/Autoload/Fixtures/autoload_functions.php
<?php // autoload.php @generated by Composer if (PHP_VERSION_ID < 50600) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } $err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL; if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, $err); } elseif (!headers_sent()) { echo $err; } } throw new RuntimeException($err); } require_once __DIR__ . '/composer/autoload_real.php'; return ComposerAutoloaderInitFilesAutoload::getLoader();
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_files_files_by_dependency.php
tests/Composer/Test/Autoload/Fixtures/autoload_files_files_by_dependency.php
<?php // autoload_files.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( $vendorDir . '/c/lorem/testC.php', $vendorDir . '/z/foo/testA.php', $vendorDir . '/d/d/testD.php', $vendorDir . '/b/bar/testB.php', $vendorDir . '/e/e/testE.php', $baseDir . '/root.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_real_functions_with_removed_include_paths_and_autolad_files.php
tests/Composer/Test/Autoload/Fixtures/autoload_real_functions_with_removed_include_paths_and_autolad_files.php
<?php // autoload_real.php @generated by Composer class ComposerAutoloaderInitFilesAutoload { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } /** * @return \Composer\Autoload\ClassLoader */ public static function getLoader() { if (null !== self::$loader) { return self::$loader; } spl_autoload_register(array('ComposerAutoloaderInitFilesAutoload', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__)); spl_autoload_unregister(array('ComposerAutoloaderInitFilesAutoload', 'loadClassLoader')); require __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInitFilesAutoload::getInitializer($loader)); $loader->register(true); return $loader; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_classmap.php
tests/Composer/Test/Autoload/Fixtures/autoload_classmap.php
<?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'Acme\\Cake\\ClassMapBar' => $baseDir . '/src-cake/ClassMapBar.php', 'ClassMapFoo' => $baseDir . '/composersrc/foo.php', 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', 'Lala\\ClassMapMain' => $baseDir . '/src/Lala/ClassMapMain.php', 'Lala\\Test\\ClassMapMainTest' => $baseDir . '/src/Lala/Test/ClassMapMainTest.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_main3.php
tests/Composer/Test/Autoload/Fixtures/autoload_main3.php
<?php // autoload_namespaces.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = $vendorDir; return array( 'Main' => array($vendorDir . '/src'), 'Lala' => array($vendorDir . '/src'), );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_vendors_meta.php
tests/Composer/Test/Autoload/Fixtures/autoload_vendors_meta.php
<?php // autoload_namespaces.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'B\\Sub\\Name' => array($vendorDir . '/b/b/src'), );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_psr4_2.php
tests/Composer/Test/Autoload/Fixtures/autoload_psr4_2.php
<?php // autoload_psr4.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname(dirname($vendorDir)); return array( 'Acme\\Fruit\\' => array($baseDir . '/src-fruit'), 'Acme\\Cake\\' => array($baseDir . '/src-cake', $baseDir . '/lib-cake'), );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_classmap6.php
tests/Composer/Test/Autoload/Fixtures/autoload_classmap6.php
<?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(__DIR__); $baseDir = dirname($vendorDir); return array( 'ClassMapBar' => $baseDir . '/lib/rootbar.php', 'ClassMapFoo' => $baseDir . '/src/rootfoo.php', 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/autoload_static_include_path.php
tests/Composer/Test/Autoload/Fixtures/autoload_static_include_path.php
<?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInitIncludePath { public static $prefixesPsr0 = array ( 'M' => array ( 'Main\\Foo' => array ( 0 => __DIR__ . '/../..' . '/', ), 'Main\\Bar' => array ( 0 => __DIR__ . '/../..' . '/', ), ), ); public static $classMap = array ( 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->prefixesPsr0 = ComposerStaticInitIncludePath::$prefixesPsr0; $loader->classMap = ComposerStaticInitIncludePath::$classMap; }, null, ClassLoader::class); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/Namespaced/Foo.php
tests/Composer/Test/Autoload/Fixtures/Namespaced/Foo.php
<?php namespace Namespaced; class Foo { public static $loaded = true; }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/Pearlike/Foo.php
tests/Composer/Test/Autoload/Fixtures/Pearlike/Foo.php
<?php class Pearlike_Foo { public static $loaded = true; }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/SubNamespace/Foo.php
tests/Composer/Test/Autoload/Fixtures/SubNamespace/Foo.php
<?php namespace ShinyVendor\ShinyPackage\SubNamespace; class Foo {}
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/SubNamespace/Bar.php
tests/Composer/Test/Autoload/Fixtures/SubNamespace/Bar.php
<?php namespace ShinyVendor\ShinyPackage\SubNamespace; class Bar {}
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/platform/replaced_provided_exts.php
tests/Composer/Test/Autoload/Fixtures/platform/replaced_provided_exts.php
<?php // platform_check.php @generated by Composer $issues = array(); $missingExtensions = array(); extension_loaded('pdo') || $missingExtensions[] = 'pdo'; if ($missingExtensions) { $issues[] = 'Your Composer dependencies require the following PHP extensions to be installed: ' . implode(', ', $missingExtensions) . '.'; } if ($issues) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); } elseif (!headers_sent()) { echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; } } throw new \RuntimeException( 'Composer detected issues in your platform: ' . implode(' ', $issues) ); }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/platform/no_php_upper_bound.php
tests/Composer/Test/Autoload/Fixtures/platform/no_php_upper_bound.php
<?php // platform_check.php @generated by Composer $issues = array(); if (!(PHP_VERSION_ID >= 70200)) { $issues[] = 'Your Composer dependencies require a PHP version ">= 7.2.0". You are running ' . PHP_VERSION . '.'; } if ($issues) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); } elseif (!headers_sent()) { echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; } } throw new \RuntimeException( 'Composer detected issues in your platform: ' . implode(' ', $issues) ); }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/platform/no_extensions_required.php
tests/Composer/Test/Autoload/Fixtures/platform/no_extensions_required.php
<?php // platform_check.php @generated by Composer $issues = array(); if (!(PHP_VERSION_ID >= 70200)) { $issues[] = 'Your Composer dependencies require a PHP version ">= 7.2.0". You are running ' . PHP_VERSION . '.'; } if ($issues) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); } elseif (!headers_sent()) { echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; } } throw new \RuntimeException( 'Composer detected issues in your platform: ' . implode(' ', $issues) ); }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/platform/php_64bit_required.php
tests/Composer/Test/Autoload/Fixtures/platform/php_64bit_required.php
<?php // platform_check.php @generated by Composer $issues = array(); if (PHP_INT_SIZE !== 8) { $issues[] = 'Your Composer dependencies require a 64-bit build of PHP.'; } if ($issues) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); } elseif (!headers_sent()) { echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; } } throw new \RuntimeException( 'Composer detected issues in your platform: ' . implode(' ', $issues) ); }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/platform/specific_php_64bit_required.php
tests/Composer/Test/Autoload/Fixtures/platform/specific_php_64bit_required.php
<?php // platform_check.php @generated by Composer $issues = array(); if (!(PHP_VERSION_ID >= 70208)) { $issues[] = 'Your Composer dependencies require a PHP version ">= 7.2.8". You are running ' . PHP_VERSION . '.'; } if (PHP_INT_SIZE !== 8) { $issues[] = 'Your Composer dependencies require a 64-bit build of PHP.'; } if ($issues) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); } elseif (!headers_sent()) { echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; } } throw new \RuntimeException( 'Composer detected issues in your platform: ' . implode(' ', $issues) ); }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/platform/no_php_required.php
tests/Composer/Test/Autoload/Fixtures/platform/no_php_required.php
<?php // platform_check.php @generated by Composer $issues = array(); $missingExtensions = array(); extension_loaded('json') || $missingExtensions[] = 'json'; extension_loaded('xml') || $missingExtensions[] = 'xml'; if ($missingExtensions) { $issues[] = 'Your Composer dependencies require the following PHP extensions to be installed: ' . implode(', ', $missingExtensions) . '.'; } if ($issues) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); } elseif (!headers_sent()) { echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; } } throw new \RuntimeException( 'Composer detected issues in your platform: ' . implode(' ', $issues) ); }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/platform/specific_php_release.php
tests/Composer/Test/Autoload/Fixtures/platform/specific_php_release.php
<?php // platform_check.php @generated by Composer $issues = array(); if (!(PHP_VERSION_ID >= 70208)) { $issues[] = 'Your Composer dependencies require a PHP version ">= 7.2.8". You are running ' . PHP_VERSION . '.'; } if ($issues) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); } elseif (!headers_sent()) { echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; } } throw new \RuntimeException( 'Composer detected issues in your platform: ' . implode(' ', $issues) ); }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Autoload/Fixtures/platform/typical.php
tests/Composer/Test/Autoload/Fixtures/platform/typical.php
<?php // platform_check.php @generated by Composer $issues = array(); if (!(PHP_VERSION_ID >= 70200)) { $issues[] = 'Your Composer dependencies require a PHP version ">= 7.2.0". You are running ' . PHP_VERSION . '.'; } $missingExtensions = array(); extension_loaded('json') || $missingExtensions[] = 'json'; extension_loaded('xml') || $missingExtensions[] = 'xml'; if ($missingExtensions) { $issues[] = 'Your Composer dependencies require the following PHP extensions to be installed: ' . implode(', ', $missingExtensions) . '.'; } if ($issues) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); } elseif (!headers_sent()) { echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; } } throw new \RuntimeException( 'Composer detected issues in your platform: ' . implode(' ', $issues) ); }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Script/EventTest.php
tests/Composer/Test/Script/EventTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Script; use Composer\Composer; use Composer\Config; use Composer\Script\Event; use Composer\Test\TestCase; class EventTest extends TestCase { public function testEventSetsOriginatingEvent(): void { $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $composer = $this->createComposerInstance(); $originatingEvent = new \Composer\EventDispatcher\Event('originatingEvent'); $scriptEvent = new Event('test', $composer, $io, true); self::assertNull( $scriptEvent->getOriginatingEvent(), 'originatingEvent is initialized as null' ); $scriptEvent->setOriginatingEvent($originatingEvent); self::assertSame( $originatingEvent, $scriptEvent->getOriginatingEvent(), 'getOriginatingEvent() SHOULD return test event' ); } public function testEventCalculatesNestedOriginatingEvent(): void { $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $composer = $this->createComposerInstance(); $originatingEvent = new \Composer\EventDispatcher\Event('upperOriginatingEvent'); $intermediateEvent = new Event('intermediate', $composer, $io, true); $intermediateEvent->setOriginatingEvent($originatingEvent); $scriptEvent = new Event('test', $composer, $io, true); $scriptEvent->setOriginatingEvent($intermediateEvent); self::assertNotSame( $intermediateEvent, $scriptEvent->getOriginatingEvent(), 'getOriginatingEvent() SHOULD NOT return intermediate events' ); self::assertSame( $originatingEvent, $scriptEvent->getOriginatingEvent(), 'getOriginatingEvent() SHOULD return upper-most event' ); } private function createComposerInstance(): Composer { $composer = new Composer; $config = new Config; $composer->setConfig($config); $package = $this->getMockBuilder('Composer\Package\RootPackageInterface')->getMock(); $composer->setPackage($package); return $composer; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Mock/ProcessExecutorMock.php
tests/Composer/Test/Mock/ProcessExecutorMock.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Mock; use PHPUnit\Framework\MockObject\MockBuilder; use React\Promise\PromiseInterface; use Composer\Util\ProcessExecutor; use Composer\Util\Platform; use PHPUnit\Framework\Assert; use PHPUnit\Framework\AssertionFailedError; use Symfony\Component\Process\Process; use React\Promise\Promise; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class ProcessExecutorMock extends ProcessExecutor { /** * @var array<array{cmd: string|list<string>, return: int, stdout: string, stderr: string, callback: callable|null}>|null */ private $expectations = null; /** * @var bool */ private $strict = false; /** * @var array{return: int, stdout: string, stderr: string} */ private $defaultHandler = ['return' => 0, 'stdout' => '', 'stderr' => '']; /** * @var string[] */ private $log = []; /** * @var MockBuilder<Process> */ private $processMockBuilder; /** * @param MockBuilder<Process> $processMockBuilder */ public function __construct(MockBuilder $processMockBuilder) { parent::__construct(); $this->processMockBuilder = $processMockBuilder->disableOriginalConstructor(); } /** * @param array<string|non-empty-list<string>|array{cmd: string|non-empty-list<string>, return?: int, stdout?: string, stderr?: string, callback?: callable}> $expectations * @param bool $strict set to true if you want to provide *all* expected commands, and not just a subset you are interested in testing * @param array{return: int, stdout?: string, stderr?: string} $defaultHandler default command handler for undefined commands if not in strict mode */ public function expects(array $expectations, bool $strict = false, array $defaultHandler = ['return' => 0, 'stdout' => '', 'stderr' => '']): void { /** @var array{cmd: string|non-empty-list<string>, return: int, stdout: string, stderr: string, callback: callable|null} $default */ $default = ['cmd' => '', 'return' => 0, 'stdout' => '', 'stderr' => '', 'callback' => null]; $this->expectations = array_map(static function ($expect) use ($default): array { if (is_string($expect) || array_is_list($expect)) { $command = $expect; $expect = $default; $expect['cmd'] = $command; } elseif (count($diff = array_diff_key(array_merge($default, $expect), $default)) > 0) { throw new \UnexpectedValueException('Unexpected keys in process execution step: '.implode(', ', array_keys($diff))); } return array_merge($default, $expect); }, $expectations); $this->strict = $strict; $this->defaultHandler = array_merge($this->defaultHandler, $defaultHandler); } public function assertComplete(): void { // this was not configured to expect anything, so no need to react here if (!is_array($this->expectations)) { return; } if (count($this->expectations) > 0) { $expectations = array_map(static function ($expect): string { return is_array($expect['cmd']) ? implode(' ', $expect['cmd']) : $expect['cmd']; }, $this->expectations); throw new AssertionFailedError( 'There are still '.count($this->expectations).' expected process calls which have not been consumed:'.PHP_EOL. implode(PHP_EOL, $expectations).PHP_EOL.PHP_EOL. 'Received calls:'.PHP_EOL.implode(PHP_EOL, $this->log) ); } // dummy assertion to ensure the test is not marked as having no assertions Assert::assertTrue(true); // @phpstan-ignore staticMethod.alreadyNarrowedType } public function execute($command, &$output = null, ?string $cwd = null): int { $cwd = $cwd ?? Platform::getCwd(); if (func_num_args() > 1) { return $this->doExecute($command, $cwd, false, $output); } return $this->doExecute($command, $cwd, false); } public function executeTty($command, ?string $cwd = null): int { $cwd = $cwd ?? Platform::getCwd(); if (Platform::isTty()) { return $this->doExecute($command, $cwd, true); } return $this->doExecute($command, $cwd, false); } /** * @param string|list<string> $command * @param callable|string|null $output * @return mixed */ private function doExecute($command, string $cwd, bool $tty, &$output = null) { $this->captureOutput = func_num_args() > 3; $this->errorOutput = ''; $callback = is_callable($output) ? $output : function (string $type, string $buffer): void { $this->outputHandler($type, $buffer); }; $commandString = is_array($command) ? implode(' ', $command) : $command; $this->log[] = $commandString; if (is_array($this->expectations) && count($this->expectations) > 0 && $command === $this->expectations[0]['cmd']) { $expect = array_shift($this->expectations); $stdout = $expect['stdout']; $stderr = $expect['stderr']; $return = $expect['return']; if (isset($expect['callback'])) { $expect['callback'](); } } elseif (!$this->strict) { $stdout = $this->defaultHandler['stdout']; $stderr = $this->defaultHandler['stderr']; $return = $this->defaultHandler['return']; } else { throw new AssertionFailedError( 'Received unexpected command '.var_export($command, true).' in "'.$cwd.'"'.PHP_EOL. (is_array($this->expectations) && count($this->expectations) > 0 ? 'Expected '.var_export($this->expectations[0]['cmd'], true).' at this point.' : 'Expected no more calls at this point.').PHP_EOL. 'Received calls:'.PHP_EOL.implode(PHP_EOL, array_slice($this->log, 0, -1)) ); } if ($stdout) { $callback(Process::OUT, $stdout); } if ($stderr) { $callback(Process::ERR, $stderr); } if ($this->captureOutput && !is_callable($output)) { $output = $stdout; } $this->errorOutput = $stderr; return $return; } public function executeAsync($command, ?string $cwd = null): PromiseInterface { $cwd = $cwd ?? Platform::getCwd(); $resolver = function ($resolve, $reject) use ($command, $cwd): void { $result = $this->doExecute($command, $cwd, false, $output); $procMock = $this->processMockBuilder->getMock(); $procMock->method('getOutput')->willReturn($output); $procMock->method('isSuccessful')->willReturn($result === 0); $procMock->method('getExitCode')->willReturn($result); $resolve($procMock); }; $canceler = static function (): void { throw new \RuntimeException('Aborted process'); }; return new Promise($resolver, $canceler); } public function getErrorOutput(): string { return $this->errorOutput; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Mock/InstallationManagerMock.php
tests/Composer/Test/Mock/InstallationManagerMock.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Mock; use React\Promise\PromiseInterface; use Composer\Installer\InstallationManager; use Composer\Repository\InstalledRepositoryInterface; use Composer\Package\PackageInterface; use Composer\IO\IOInterface; use Composer\DependencyResolver\Operation\InstallOperation; use Composer\DependencyResolver\Operation\UpdateOperation; use Composer\DependencyResolver\Operation\UninstallOperation; use Composer\DependencyResolver\Operation\MarkAliasInstalledOperation; use Composer\DependencyResolver\Operation\MarkAliasUninstalledOperation; class InstallationManagerMock extends InstallationManager { /** * @var PackageInterface[] */ private $installed = []; /** * @var PackageInterface[][] */ private $updated = []; /** * @var PackageInterface[] */ private $uninstalled = []; /** * @var string[] */ private $trace = []; public function __construct() { } public function execute(InstalledRepositoryInterface $repo, array $operations, $devMode = true, $runScripts = true, $downloadOnly = false): void { foreach ($operations as $operation) { $method = $operation->getOperationType(); // skipping download() step here for tests $this->{$method}($repo, $operation); } } public function getInstallPath(PackageInterface $package): string { return 'vendor/'.$package->getName(); } public function isPackageInstalled(InstalledRepositoryInterface $repo, PackageInterface $package): bool { return $repo->hasPackage($package); } /** * @inheritDoc */ public function install(InstalledRepositoryInterface $repo, InstallOperation $operation): ?PromiseInterface { $this->installed[] = $operation->getPackage(); $this->trace[] = strip_tags((string) $operation); $repo->addPackage(clone $operation->getPackage()); return null; } /** * @inheritDoc */ public function update(InstalledRepositoryInterface $repo, UpdateOperation $operation): ?PromiseInterface { $this->updated[] = [$operation->getInitialPackage(), $operation->getTargetPackage()]; $this->trace[] = strip_tags((string) $operation); $repo->removePackage($operation->getInitialPackage()); if (!$repo->hasPackage($operation->getTargetPackage())) { $repo->addPackage(clone $operation->getTargetPackage()); } return null; } /** * @inheritDoc */ public function uninstall(InstalledRepositoryInterface $repo, UninstallOperation $operation): ?PromiseInterface { $this->uninstalled[] = $operation->getPackage(); $this->trace[] = strip_tags((string) $operation); $repo->removePackage($operation->getPackage()); return null; } public function markAliasInstalled(InstalledRepositoryInterface $repo, MarkAliasInstalledOperation $operation): void { $package = $operation->getPackage(); $this->installed[] = $package; $this->trace[] = strip_tags((string) $operation); parent::markAliasInstalled($repo, $operation); } public function markAliasUninstalled(InstalledRepositoryInterface $repo, MarkAliasUninstalledOperation $operation): void { $this->uninstalled[] = $operation->getPackage(); $this->trace[] = strip_tags((string) $operation); parent::markAliasUninstalled($repo, $operation); } /** @return string[] */ public function getTrace(): array { return $this->trace; } /** @return PackageInterface[] */ public function getInstalledPackages(): array { return $this->installed; } /** @return PackageInterface[][] */ public function getUpdatedPackages(): array { return $this->updated; } /** @return PackageInterface[] */ public function getUninstalledPackages(): array { return $this->uninstalled; } public function notifyInstalls(IOInterface $io): void { // noop } /** @return PackageInterface[] */ public function getInstalledPackagesByType(): array { return $this->installed; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Mock/VersionGuesserMock.php
tests/Composer/Test/Mock/VersionGuesserMock.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Mock; use Composer\Package\Version\VersionGuesser; class VersionGuesserMock extends VersionGuesser { public function __construct() { } public function guessVersion(array $packageConfig, $path): ?array { return null; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Mock/HttpDownloaderMock.php
tests/Composer/Test/Mock/HttpDownloaderMock.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Mock; use Composer\Config; use Composer\IO\BufferIO; use Composer\IO\IOInterface; use Composer\Util\HttpDownloader; use Composer\Util\Http\Response; use Composer\Downloader\TransportException; use PHPUnit\Framework\Assert; use PHPUnit\Framework\AssertionFailedError; class HttpDownloaderMock extends HttpDownloader { /** * @var array<array{url: non-empty-string, options: array<mixed>|null, status: int, body: string, headers: list<string>}>|null */ private $expectations = null; /** * @var bool */ private $strict = false; /** * @var array{status: int, body: string, headers: list<string>} */ private $defaultHandler = ['status' => 200, 'body' => '', 'headers' => []]; /** * @var string[] */ private $log = []; public function __construct(?IOInterface $io = null, ?Config $config = null) { if ($io === null) { $io = new BufferIO(); } if ($config === null) { $config = new Config(false); } parent::__construct($io, $config); } /** * @param array<array{url: non-empty-string, options?: array<mixed>, status?: int, body?: string, headers?: list<string>}> $expectations * @param bool $strict set to true if you want to provide *all* expected http requests, and not just a subset you are interested in testing * @param array{status?: int, body?: string, headers?: list<string>} $defaultHandler default URL handler for undefined requests if not in strict mode */ public function expects(array $expectations, bool $strict = false, array $defaultHandler = ['status' => 200, 'body' => '', 'headers' => []]): void { $default = ['url' => '', 'options' => null, 'status' => 200, 'body' => '', 'headers' => ['']]; $this->expectations = array_map(static function (array $expect) use ($default): array { if (count($diff = array_diff_key(array_merge($default, $expect), $default)) > 0) { throw new \UnexpectedValueException('Unexpected keys in process execution step: '.implode(', ', array_keys($diff))); } return array_merge($default, $expect); }, $expectations); $this->strict = $strict; $this->defaultHandler = array_merge($this->defaultHandler, $defaultHandler); } public function assertComplete(): void { // this was not configured to expect anything, so no need to react here if (!is_array($this->expectations)) { return; } if (count($this->expectations) > 0) { $expectations = array_map(static function ($expect): string { return $expect['url']; }, $this->expectations); throw new AssertionFailedError( 'There are still '.count($this->expectations).' expected HTTP requests which have not been consumed:'.PHP_EOL. implode(PHP_EOL, $expectations).PHP_EOL.PHP_EOL. 'Received calls:'.PHP_EOL.implode(PHP_EOL, $this->log) ); } // dummy assertion to ensure the test is not marked as having no assertions Assert::assertTrue(true); // @phpstan-ignore staticMethod.alreadyNarrowedType } public function get($fileUrl, $options = []): Response { if ('' === $fileUrl) { throw new \LogicException('url cannot be an empty string'); } $this->log[] = $fileUrl; if (is_array($this->expectations) && count($this->expectations) > 0 && $fileUrl === $this->expectations[0]['url'] && ($this->expectations[0]['options'] === null || $options === $this->expectations[0]['options'])) { $expect = array_shift($this->expectations); return $this->respond($fileUrl, $expect['status'], $expect['headers'], $expect['body']); } if (!$this->strict) { return $this->respond($fileUrl, $this->defaultHandler['status'], $this->defaultHandler['headers'], $this->defaultHandler['body']); } throw new AssertionFailedError( 'Received unexpected request for "'.$fileUrl.'" with options "'.json_encode($options).'"'.PHP_EOL. (is_array($this->expectations) && count($this->expectations) > 0 ? 'Expected "'.$this->expectations[0]['url'].($this->expectations[0]['options'] !== null ? '" with options "'.json_encode($this->expectations[0]['options']) : '').'" at this point.' : 'Expected no more calls at this point.').PHP_EOL. 'Received calls:'.PHP_EOL.implode(PHP_EOL, array_slice($this->log, 0, -1)) ); } /** * @param list<string> $headers * @param non-empty-string $url */ private function respond(string $url, int $status, array $headers, string $body): Response { if ($status < 400) { return new Response(['url' => $url], $status, $headers, $body); } $e = new TransportException('The "'.$url.'" file could not be downloaded', $status); $e->setHeaders($headers); $e->setResponse($body); throw $e; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Mock/InstalledFilesystemRepositoryMock.php
tests/Composer/Test/Mock/InstalledFilesystemRepositoryMock.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Mock; use Composer\Repository\InstalledFilesystemRepository; use Composer\Installer\InstallationManager; class InstalledFilesystemRepositoryMock extends InstalledFilesystemRepository { public function reload(): void { } public function write($devMode, InstallationManager $installationManager): void { } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Mock/FactoryMock.php
tests/Composer/Test/Mock/FactoryMock.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Mock; use Composer\Installer\InstallationManager; use Composer\Package\Loader\RootPackageLoader; use Composer\Config; use Composer\Factory; use Composer\PartialComposer; use Composer\Repository\RepositoryManager; use Composer\Package\Version\VersionGuesser; use Composer\Package\Version\VersionParser; use Composer\Package\RootPackageInterface; use Composer\EventDispatcher\EventDispatcher; use Composer\IO\IOInterface; use Composer\Repository\InstalledArrayRepository; use Composer\Repository\InstalledRepositoryInterface; use Composer\Test\TestCase; use Composer\Util\Loop; use Composer\Util\ProcessExecutor; class FactoryMock extends Factory { public static function createConfig(?IOInterface $io = null, ?string $cwd = null): Config { $config = new Config(true, $cwd); $config->merge([ 'config' => ['home' => TestCase::getUniqueTmpDirectory()], 'repositories' => ['packagist' => false], ]); return $config; } protected function loadRootPackage(RepositoryManager $rm, Config $config, VersionParser $parser, VersionGuesser $guesser, IOInterface $io): RootPackageLoader { return new RootPackageLoader($rm, $config, $parser, new VersionGuesserMock(), $io); } protected function addLocalRepository(IOInterface $io, RepositoryManager $rm, string $vendorDir, RootPackageInterface $rootPackage, ?ProcessExecutor $process = null): void { $rm->setLocalRepository(new InstalledArrayRepository); } public function createInstallationManager(?Loop $loop = null, ?IOInterface $io = null, ?EventDispatcher $dispatcher = null): InstallationManager { return new InstallationManagerMock(); } protected function createDefaultInstallers(InstallationManager $im, PartialComposer $composer, IOInterface $io, ?ProcessExecutor $process = null): void { } protected function purgePackages(InstalledRepositoryInterface $repo, InstallationManager $im): void { } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Mock/IOMock.php
tests/Composer/Test/Mock/IOMock.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Mock; use Composer\IO\BufferIO; use Composer\IO\IOInterface; use Composer\Pcre\PcreException; use Composer\Pcre\Preg; use Composer\Util\Platform; use LogicException; use PHPUnit\Framework\Assert; use PHPUnit\Framework\AssertionFailedError; use Symfony\Component\Console\Output\OutputInterface; class IOMock extends BufferIO { /** * @var list<array{text: string, verbosity?: IOInterface::*}|array{ask: string, reply?: string}|array{auth: array{string, string, string|null}}>|null */ private $expectations = null; /** * @var bool */ private $strict = false; /** * @var list<array{string, string, string|null}> */ private $authLog = []; /** * @param IOInterface::* $verbosity */ public function __construct(int $verbosity) { $sfVerbosity = [ self::QUIET => OutputInterface::VERBOSITY_QUIET, self::NORMAL => OutputInterface::VERBOSITY_NORMAL, self::VERBOSE => OutputInterface::VERBOSITY_VERBOSE, self::VERY_VERBOSE => OutputInterface::VERBOSITY_VERY_VERBOSE, self::DEBUG => OutputInterface::VERBOSITY_DEBUG, ][$verbosity]; parent::__construct('', $sfVerbosity); } /** * @param list<array{text: string, verbosity?: IOInterface::*, regex?: true}|array{ask: string, reply: string}|array{auth: array{string, string, string|null}}> $expectations * @param bool $strict set to true if you want to provide *all* expected messages, and not just a subset you are interested in testing */ public function expects(array $expectations, bool $strict = false): void { $this->expectations = $expectations; $inputs = []; foreach ($expectations as $expect) { if (isset($expect['ask'])) { if (!array_key_exists('reply', $expect) || !is_string($expect['reply'])) { throw new LogicException('A question\'s reply must be a string, use empty string for null replies'); } $inputs[] = $expect['reply']; } } if (count($inputs) > 0) { $this->setUserInputs($inputs); } $this->strict = $strict; } public function assertComplete(): void { $output = $this->getOutput(); if (Platform::getEnv('DEBUG_OUTPUT') === '1') { echo PHP_EOL.'Collected output: '.$output.PHP_EOL; } // this was not configured to expect anything, so no need to react here if (!is_array($this->expectations)) { return; } if (count($this->expectations) > 0) { $lines = Preg::split("{\r?\n}", $output); foreach ($this->expectations as $expect) { if (isset($expect['auth'])) { while (count($this->authLog) > 0) { $auth = array_shift($this->authLog); if ($auth === $expect['auth']) { continue 2; } if ($this->strict) { throw new AssertionFailedError('IO authentication mismatch. Expected:'.PHP_EOL.json_encode($expect['auth']).PHP_EOL.'Got:'.PHP_EOL.json_encode($auth)); } } throw new AssertionFailedError('Expected "'.json_encode($expect['auth']).'" auth to be set but there are no setAuthentication calls left to consume.'); } if (isset($expect['ask'], $expect['reply'])) { $pattern = '{^'.preg_quote($expect['ask']).'$}'; } elseif (isset($expect['regex']) && $expect['regex']) { $pattern = $expect['text']; } else { $pattern = '{^'.preg_quote($expect['text']).'$}'; } while (count($lines) > 0) { $line = array_shift($lines); try { if (Preg::isMatch($pattern, $line)) { continue 2; } } catch (PcreException $e) { throw new LogicException('Invalid regex pattern in IO expectation "'.$pattern.'": '.$e->getMessage()); } if ($this->strict) { throw new AssertionFailedError('IO output mismatch. Expected:'.PHP_EOL.($expect['text'] ?? $expect['ask']).PHP_EOL.'Got:'.PHP_EOL.$line); } } throw new AssertionFailedError('Expected "'.($expect['text'] ?? $expect['ask']).'" to be output still but there is no output left to consume. Complete output:'.PHP_EOL.$output); } } elseif ($output !== '' && $this->strict) { throw new AssertionFailedError('There was strictly no output expected but some output occurred: '.$output); } // dummy assertion to ensure the test is not marked as having no assertions Assert::assertTrue(true); // @phpstan-ignore staticMethod.alreadyNarrowedType } /** * @inheritDoc */ public function ask($question, $default = null) { return parent::ask(rtrim($question, "\r\n").PHP_EOL, $default); } /** * @inheritDoc */ public function askConfirmation($question, $default = true) { return parent::askConfirmation(rtrim($question, "\r\n").PHP_EOL, $default); } /** * @inheritDoc */ public function askAndValidate($question, $validator, $attempts = null, $default = null) { return parent::askAndValidate(rtrim($question, "\r\n").PHP_EOL, $validator, $attempts, $default); } /** * @inheritDoc */ public function askAndHideAnswer($question) { // do not hide answer in tests because that blocks on windows with hiddeninput.exe return parent::ask(rtrim($question, "\r\n").PHP_EOL); } /** * @inheritDoc */ public function select($question, $choices, $default, $attempts = false, $errorMessage = 'Value "%s" is invalid', $multiselect = false) { return parent::select(rtrim($question, "\r\n").PHP_EOL, $choices, $default, $attempts, $errorMessage, $multiselect); } public function setAuthentication($repositoryName, $username, $password = null) { $this->authentications[$repositoryName] = ['username' => $username, 'password' => $password]; $this->authLog[] = [$repositoryName, $username, $password]; parent::setAuthentication($repositoryName, $username, $password); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Plugin/PluginInstallerTest.php
tests/Composer/Test/Plugin/PluginInstallerTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Plugin; use Composer\Composer; use Composer\Config; use Composer\Installer\PluginInstaller; use Composer\Json\JsonFile; use Composer\Package\CompleteAliasPackage; use Composer\Package\CompletePackage; use Composer\Package\Loader\JsonLoader; use Composer\Package\Loader\ArrayLoader; use Composer\Package\Locker; use Composer\Package\RootPackage; use Composer\Plugin\PluginManager; use Composer\IO\BufferIO; use Composer\EventDispatcher\EventDispatcher; use Composer\Autoload\AutoloadGenerator; use Composer\Test\TestCase; use Composer\Util\Filesystem; use Composer\Util\Platform; class PluginInstallerTest extends TestCase { /** * @var Composer */ protected $composer; /** * @var PluginManager */ protected $pm; /** * @var AutoloadGenerator */ protected $autoloadGenerator; /** * @var array<CompletePackage|CompleteAliasPackage> */ protected $packages; /** * @var string */ protected $directory; /** * @var \PHPUnit\Framework\MockObject\MockObject&\Composer\Installer\InstallationManager */ protected $im; /** * @var \PHPUnit\Framework\MockObject\MockObject&\Composer\Repository\InstalledRepositoryInterface */ protected $repository; /** * @var BufferIO */ protected $io; protected function setUp(): void { $loader = new JsonLoader(new ArrayLoader()); $this->packages = []; $this->directory = self::getUniqueTmpDirectory(); for ($i = 1; $i <= 8; $i++) { $filename = '/Fixtures/plugin-v'.$i.'/composer.json'; mkdir(dirname($this->directory . $filename), 0777, true); $this->packages[] = $loader->load(__DIR__ . $filename); } $dm = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->disableOriginalConstructor() ->getMock(); $dm->expects($this->any()) ->method('install') ->will($this->returnValue(\React\Promise\resolve(null))); $dm->expects($this->any()) ->method('update') ->will($this->returnValue(\React\Promise\resolve(null))); $dm->expects($this->any()) ->method('remove') ->will($this->returnValue(\React\Promise\resolve(null))); $this->repository = $this->getMockBuilder('Composer\Repository\InstalledRepositoryInterface')->getMock(); $rm = $this->getMockBuilder('Composer\Repository\RepositoryManager') ->disableOriginalConstructor() ->getMock(); $rm->expects($this->any()) ->method('getLocalRepository') ->will($this->returnValue($this->repository)); $im = $this->getMockBuilder('Composer\Installer\InstallationManager')->disableOriginalConstructor()->getMock(); $im->expects($this->any()) ->method('getInstallPath') ->will($this->returnCallback(static function ($package): string { return __DIR__.'/Fixtures/'.$package->getPrettyName(); })); $this->io = new BufferIO(); $dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock(); $this->autoloadGenerator = new AutoloadGenerator($dispatcher); $this->composer = new Composer(); $config = new Config(false); $this->composer->setConfig($config); $this->composer->setDownloadManager($dm); $this->composer->setRepositoryManager($rm); $this->composer->setInstallationManager($im); $this->composer->setAutoloadGenerator($this->autoloadGenerator); $this->composer->setEventDispatcher(new EventDispatcher($this->composer, $this->io)); $this->composer->setPackage(new RootPackage('dummy/root', '1.0.0.0', '1.0.0')); $this->composer->setLocker(new Locker($this->io, new JsonFile(Platform::getDevNull()), $im, '{}')); $config->merge([ 'config' => [ 'vendor-dir' => $this->directory.'/Fixtures/', 'home' => $this->directory.'/Fixtures', 'bin-dir' => $this->directory.'/Fixtures/bin', 'allow-plugins' => true, ], ]); $this->pm = new PluginManager($this->io, $this->composer); $this->composer->setPluginManager($this->pm); } protected function tearDown(): void { parent::tearDown(); $filesystem = new Filesystem(); $filesystem->removeDirectory($this->directory); } public function testInstallNewPlugin(): void { $this->repository ->expects($this->any()) ->method('getPackages') ->will($this->returnValue([])); $installer = new PluginInstaller($this->io, $this->composer); $this->pm->loadInstalledPlugins(); $installer->install($this->repository, $this->packages[0]); $plugins = $this->pm->getPlugins(); self::assertEquals('installer-v1', $plugins[0]->version); // @phpstan-ignore property.notFound self::assertEquals( 'activate v1'.PHP_EOL, $this->io->getOutput() ); } public function testInstallPluginWithRootPackageHavingFilesAutoload(): void { $this->repository ->expects($this->any()) ->method('getPackages') ->will($this->returnValue([])); $installer = new PluginInstaller($this->io, $this->composer); $this->pm->loadInstalledPlugins(); $this->autoloadGenerator->setDevMode(true); $this->composer->getPackage()->setAutoload(['files' => [__DIR__ . '/Fixtures/files_autoload_which_should_not_run.php']]); $this->composer->getPackage()->setDevAutoload(['files' => [__DIR__ . '/Fixtures/files_autoload_which_should_not_run.php']]); $installer->install($this->repository, $this->packages[0]); $plugins = $this->pm->getPlugins(); self::assertEquals( 'activate v1'.PHP_EOL, $this->io->getOutput() ); self::assertEquals('installer-v1', $plugins[0]->version); // @phpstan-ignore property.notFound } public function testInstallMultiplePlugins(): void { $this->repository ->expects($this->any()) ->method('getPackages') ->will($this->returnValue([$this->packages[3]])); $installer = new PluginInstaller($this->io, $this->composer); $this->pm->loadInstalledPlugins(); $installer->install($this->repository, $this->packages[3]); $plugins = $this->pm->getPlugins(); self::assertEquals('plugin1', $plugins[0]->name); // @phpstan-ignore property.notFound self::assertEquals('installer-v4', $plugins[0]->version); // @phpstan-ignore property.notFound self::assertEquals('plugin2', $plugins[1]->name); // @phpstan-ignore property.notFound self::assertEquals('installer-v4', $plugins[1]->version); // @phpstan-ignore property.notFound self::assertEquals('activate v4-plugin1'.PHP_EOL.'activate v4-plugin2'.PHP_EOL, $this->io->getOutput()); } public function testUpgradeWithNewClassName(): void { $this->repository ->expects($this->any()) ->method('getPackages') ->will($this->returnValue([$this->packages[0]])); $this->repository ->expects($this->exactly(2)) ->method('hasPackage') ->will($this->onConsecutiveCalls(true, false)); $installer = new PluginInstaller($this->io, $this->composer); $this->pm->loadInstalledPlugins(); $installer->update($this->repository, $this->packages[0], $this->packages[1]); $plugins = $this->pm->getPlugins(); self::assertCount(1, $plugins); self::assertEquals('installer-v2', $plugins[1]->version); // @phpstan-ignore property.notFound self::assertEquals('activate v1'.PHP_EOL.'deactivate v1'.PHP_EOL.'activate v2'.PHP_EOL, $this->io->getOutput()); } public function testUninstall(): void { $this->repository ->expects($this->any()) ->method('getPackages') ->will($this->returnValue([$this->packages[0]])); $this->repository ->expects($this->exactly(1)) ->method('hasPackage') ->will($this->onConsecutiveCalls(true, false)); $installer = new PluginInstaller($this->io, $this->composer); $this->pm->loadInstalledPlugins(); $installer->uninstall($this->repository, $this->packages[0]); $plugins = $this->pm->getPlugins(); self::assertCount(0, $plugins); self::assertEquals('activate v1'.PHP_EOL.'deactivate v1'.PHP_EOL.'uninstall v1'.PHP_EOL, $this->io->getOutput()); } public function testUpgradeWithSameClassName(): void { $this->repository ->expects($this->any()) ->method('getPackages') ->will($this->returnValue([$this->packages[1]])); $this->repository ->expects($this->exactly(2)) ->method('hasPackage') ->will($this->onConsecutiveCalls(true, false)); $installer = new PluginInstaller($this->io, $this->composer); $this->pm->loadInstalledPlugins(); $installer->update($this->repository, $this->packages[1], $this->packages[2]); $plugins = $this->pm->getPlugins(); self::assertEquals('installer-v3', $plugins[1]->version); // @phpstan-ignore property.notFound self::assertEquals('activate v2'.PHP_EOL.'deactivate v2'.PHP_EOL.'activate v3'.PHP_EOL, $this->io->getOutput()); } public function testRegisterPluginOnlyOneTime(): void { $this->repository ->expects($this->any()) ->method('getPackages') ->will($this->returnValue([])); $installer = new PluginInstaller($this->io, $this->composer); $this->pm->loadInstalledPlugins(); $installer->install($this->repository, $this->packages[0]); $installer->install($this->repository, clone $this->packages[0]); $plugins = $this->pm->getPlugins(); self::assertCount(1, $plugins); self::assertEquals('installer-v1', $plugins[0]->version); // @phpstan-ignore property.notFound self::assertEquals('activate v1'.PHP_EOL, $this->io->getOutput()); } /** * @param array<CompletePackage|CompleteAliasPackage> $plugins */ private function setPluginApiVersionWithPlugins(string $newPluginApiVersion, array $plugins = []): void { // reset the plugin manager's installed plugins $this->pm = $this->getMockBuilder('Composer\Plugin\PluginManager') ->onlyMethods(['getPluginApiVersion']) ->setConstructorArgs([$this->io, $this->composer]) ->getMock(); // mock the Plugin API version $this->pm->expects($this->any()) ->method('getPluginApiVersion') ->will($this->returnValue($newPluginApiVersion)); $plugApiInternalPackage = self::getPackage( 'composer-plugin-api', $newPluginApiVersion, 'Composer\Package\CompletePackage' ); // Add the plugins to the repo along with the internal Plugin package on which they all rely. $this->repository ->expects($this->any()) ->method('getPackages') ->will($this->returnCallback(static function () use ($plugApiInternalPackage, $plugins): array { return array_merge([$plugApiInternalPackage], $plugins); })); $this->pm->loadInstalledPlugins(); } public function testStarPluginVersionWorksWithAnyAPIVersion(): void { $starVersionPlugin = [$this->packages[4]]; $this->setPluginApiVersionWithPlugins('1.0.0', $starVersionPlugin); self::assertCount(1, $this->pm->getPlugins()); $this->setPluginApiVersionWithPlugins('1.9.9', $starVersionPlugin); self::assertCount(1, $this->pm->getPlugins()); $this->setPluginApiVersionWithPlugins('2.0.0-dev', $starVersionPlugin); self::assertCount(1, $this->pm->getPlugins()); $this->setPluginApiVersionWithPlugins('100.0.0-stable', $starVersionPlugin); self::assertCount(1, $this->pm->getPlugins()); } public function testPluginConstraintWorksOnlyWithCertainAPIVersion(): void { $pluginWithApiConstraint = [$this->packages[5]]; $this->setPluginApiVersionWithPlugins('1.0.0', $pluginWithApiConstraint); self::assertCount(0, $this->pm->getPlugins()); $this->setPluginApiVersionWithPlugins('1.1.9', $pluginWithApiConstraint); self::assertCount(0, $this->pm->getPlugins()); $this->setPluginApiVersionWithPlugins('1.2.0', $pluginWithApiConstraint); self::assertCount(1, $this->pm->getPlugins()); $this->setPluginApiVersionWithPlugins('1.9.9', $pluginWithApiConstraint); self::assertCount(1, $this->pm->getPlugins()); } public function testPluginRangeConstraintsWorkOnlyWithCertainAPIVersion(): void { $pluginWithApiConstraint = [$this->packages[6]]; $this->setPluginApiVersionWithPlugins('1.0.0', $pluginWithApiConstraint); self::assertCount(0, $this->pm->getPlugins()); $this->setPluginApiVersionWithPlugins('3.0.0', $pluginWithApiConstraint); self::assertCount(1, $this->pm->getPlugins()); $this->setPluginApiVersionWithPlugins('5.5.0', $pluginWithApiConstraint); self::assertCount(0, $this->pm->getPlugins()); } public function testCommandProviderCapability(): void { $this->repository ->expects($this->any()) ->method('getPackages') ->will($this->returnValue([$this->packages[7]])); $installer = new PluginInstaller($this->io, $this->composer); $this->pm->loadInstalledPlugins(); /** @var \Composer\Plugin\Capability\CommandProvider[] $caps */ $caps = $this->pm->getPluginCapabilities('Composer\Plugin\Capability\CommandProvider', ['composer' => $this->composer, 'io' => $this->io]); self::assertCount(1, $caps); self::assertInstanceOf('Composer\Plugin\Capability\CommandProvider', $caps[0]); $commands = $caps[0]->getCommands(); self::assertCount(1, $commands); self::assertInstanceOf('Composer\Command\BaseCommand', $commands[0]); } public function testIncapablePluginIsCorrectlyDetected(): void { $plugin = $this->getMockBuilder('Composer\Plugin\PluginInterface') ->getMock(); self::assertNull($this->pm->getPluginCapability($plugin, 'Fake\Ability')); } public function testCapabilityImplementsComposerPluginApiClassAndIsConstructedWithArgs(): void { $capabilityApi = 'Composer\Plugin\Capability\Capability'; $capabilityImplementation = 'Composer\Test\Plugin\Mock\Capability'; $plugin = $this->getMockBuilder('Composer\Test\Plugin\Mock\CapablePluginInterface') ->getMock(); $plugin->expects($this->once()) ->method('getCapabilities') ->will($this->returnCallback(static function () use ($capabilityImplementation, $capabilityApi): array { return [$capabilityApi => $capabilityImplementation]; })); /** @var Mock\Capability $capability */ $capability = $this->pm->getPluginCapability($plugin, $capabilityApi, ['a' => 1, 'b' => 2]); self::assertInstanceOf($capabilityApi, $capability); self::assertInstanceOf($capabilityImplementation, $capability); self::assertSame(['a' => 1, 'b' => 2, 'plugin' => $plugin], $capability->args); } /** @return mixed[] */ public static function invalidImplementationClassNames(): array { return [ [null], [""], [0], [1000], [" "], [[1]], [[]], [new \stdClass()], ]; } /** * @dataProvider invalidImplementationClassNames * @param mixed $invalidImplementationClassNames * @param class-string<\Throwable> $expect */ public function testQueryingWithInvalidCapabilityClassNameThrows($invalidImplementationClassNames, string $expect = 'UnexpectedValueException'): void { self::expectException($expect); $capabilityApi = 'Composer\Plugin\Capability\Capability'; $plugin = $this->getMockBuilder('Composer\Test\Plugin\Mock\CapablePluginInterface') ->getMock(); $plugin->expects($this->once()) ->method('getCapabilities') ->will($this->returnCallback(static function () use ($invalidImplementationClassNames, $capabilityApi): array { return [$capabilityApi => $invalidImplementationClassNames]; })); $this->pm->getPluginCapability($plugin, $capabilityApi); } public function testQueryingNonProvidedCapabilityReturnsNullSafely(): void { $capabilityApi = 'Composer\Plugin\Capability\MadeUpCapability'; $plugin = $this->getMockBuilder('Composer\Test\Plugin\Mock\CapablePluginInterface') ->getMock(); $plugin->expects($this->once()) ->method('getCapabilities') ->will($this->returnCallback(static function (): array { return []; })); self::assertNull($this->pm->getPluginCapability($plugin, $capabilityApi)); } /** @return mixed[] */ public static function nonExistingOrInvalidImplementationClassTypes(): array { return [ ['\stdClass'], ['NonExistentClassLikeMiddleClass'], ]; } /** * @dataProvider nonExistingOrInvalidImplementationClassTypes */ public function testQueryingWithNonExistingOrWrongCapabilityClassTypesThrows(string $wrongImplementationClassTypes): void { $this->testQueryingWithInvalidCapabilityClassNameThrows($wrongImplementationClassTypes, 'RuntimeException'); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Plugin/Fixtures/files_autoload_which_should_not_run.php
tests/Composer/Test/Plugin/Fixtures/files_autoload_which_should_not_run.php
<?php throw new \LogicException('This file should not be autoloaded');
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false