diff --git a/src/Composer/Factory.php b/src/Composer/Factory.php index 8b7c4dbdb..3d6d58318 100644 --- a/src/Composer/Factory.php +++ b/src/Composer/Factory.php @@ -223,7 +223,19 @@ class Factory public static function getComposerFile(): string { - return trim((string) Platform::getEnv('COMPOSER')) ?: './composer.json'; + $env = Platform::getEnv('COMPOSER'); + if (is_string($env)) { + $env = trim($env); + if ('' !== $env) { + if (is_dir($env)) { + throw new \RuntimeException('The COMPOSER environment variable is set to '.$env.' which is a directory, this variable should point to a composer.json or be left unset.'); + } + + return $env; + } + } + + return './composer.json'; } public static function getLockFile(string $composerFile): string diff --git a/tests/Composer/Test/FactoryTest.php b/tests/Composer/Test/FactoryTest.php index 636e58c31..a4b5e6df1 100644 --- a/tests/Composer/Test/FactoryTest.php +++ b/tests/Composer/Test/FactoryTest.php @@ -13,9 +13,16 @@ namespace Composer\Test; use Composer\Factory; +use Composer\Util\Platform; class FactoryTest extends TestCase { + public function tearDown(): void + { + parent::tearDown(); + Platform::clearEnv('COMPOSER'); + } + /** * @group TLS */ @@ -37,4 +44,23 @@ class FactoryTest extends TestCase Factory::createHttpDownloader($ioMock, $config); } + + public function testGetComposerJsonPath(): void + { + self::assertSame('./composer.json', Factory::getComposerFile()); + } + + public function testGetComposerJsonPathFailsIfDir(): void + { + Platform::putEnv('COMPOSER', __DIR__); + self::expectException('RuntimeException'); + self::expectExceptionMessage('The COMPOSER environment variable is set to '.__DIR__.' which is a directory, this variable should point to a composer.json or be left unset.'); + Factory::getComposerFile(); + } + + public function testGetComposerJsonPathFromEnv(): void + { + Platform::putEnv('COMPOSER', ' foo.json '); + self::assertSame('foo.json', Factory::getComposerFile()); + } }