rob-revisited/ide/tests/MissingPackageTest.php

194 lines
10 KiB
PHP

<?php
namespace JumPHP\Ide\Tests;
use JumPHP\Ide\ApiPlatform\ApiInstall;
use JumPHP\Ide\Async\Deferred;
use JumPHP\Ide\Composer\ComposerProject;
use JumPHP\Ide\Composer\PackageCandidates;
use JumPHP\Ide\Composer\Packagist;
use JumPHP\Ide\Ide;
use JumPHP\Ide\Workspace\LocalWorkspace;
use PHPUnit\Framework\TestCase;
/**
* A package that is not there: `use Doctrine\ORM\Mapping as ORM;` is a namespace import (never "undefined"), a really missing class
* gets the diagnostic the quick fix hangs on, the candidates (built-in map, then Packagist), and what API Platform needs per Symfony.
*/
final class MissingPackageTest extends TestCase
{
private string $dir;
protected function setUp(): void
{
$this->dir = sys_get_temp_dir() . '/jumphp-missing-' . bin2hex(random_bytes(4));
mkdir($this->dir);
}
protected function tearDown(): void
{
exec('rm -rf ' . escapeshellarg($this->dir));
}
private function install(LocalWorkspace $ws, bool $orm, int $second): void
{
$psr4 = "<?php\n\$vendorDir = dirname(__DIR__);\n\$baseDir = dirname(\$vendorDir);\nreturn array(\n";
$installed = [];
if ($orm) {
$psr4 .= " 'Doctrine\\\\ORM\\\\' => array(\$vendorDir . '/doctrine/orm/src'),\n";
$installed[] = ['name' => 'doctrine/orm', 'version' => '3.0.0', 'install-path' => '../doctrine/orm'];
$ws->write('vendor/doctrine/orm/src/Mapping/Entity.php', "<?php\nnamespace Doctrine\\ORM\\Mapping;\n\n#[\\Attribute]\nfinal class Entity\n{\n}\n");
} else {
$ws->delete('vendor/doctrine/orm/src/Mapping/Entity.php');
}
$psr4 .= " 'App\\\\' => array(\$baseDir . '/src'),\n);\n";
$ws->write('vendor/composer/autoload_psr4.php', $psr4);
$ws->write('vendor/composer/installed.json', json_encode(['packages' => $installed]));
foreach (['vendor/composer/autoload_psr4.php', 'vendor/composer/installed.json'] as $file) {
touch("$this->dir/$file", 1_700_000_000 + $second);
}
}
private function messages(Ide $ide, string $text): array
{
return array_column($ide->handle('php.diagnostics', ['path' => 'src/Book.php', 'text' => $text]), 'message');
}
private function settle(Ide $ide): void
{
for ($i = 0; $i < 200; $i++) {
$ide->tick(0.05);
}
}
public function testANamespaceImportIsNotUndefinedButAMissingClassIs(): void
{
$ws = new LocalWorkspace($this->dir);
$ws->write('composer.json', '{"autoload": {"psr-4": {"App\\\\": "src/"}}}');
$ws->write('src/Book.php', "<?php\nnamespace App;\n\nfinal class Book\n{\n}\n");
$this->install($ws, true, 0);
$ide = new Ide($ws, $this->dir . '/cache', fn () => null);
$this->settle($ide);
$alias = "<?php\nnamespace App;\n\nuse Doctrine\\ORM\\Mapping as ORM;\n\n#[ORM\\Entity]\nfinal class Book\n{\n}\n";
self::assertSame([], $this->messages($ide, $alias), 'the namespace alias is fine');
$class = "<?php\nnamespace App;\n\nuse Doctrine\\ORM\\Mapping\\Entity;\n\n#[Entity]\nfinal class Book\n{\n}\n";
self::assertSame([], $this->messages($ide, $class), 'a class import is fine');
$missing = "<?php\nnamespace App;\n\nuse Doctrine\\Missing\\Thing;\nuse Nowhere\\Mapping as M;\n\nfinal class Book\n{\n}\n";
self::assertSame(["Undefined class 'Doctrine\\Missing\\Thing'", "Undefined class 'Nowhere\\Mapping'"], $this->messages($ide, $missing));
// composer remove doctrine/orm: the alias goes red again, the message is the one the quick fix reads
$this->install($ws, false, 20);
$ide->emit('run.exit', ['id' => 1, 'code' => 0]);
$this->settle($ide);
$after = $this->messages($ide, $alias);
self::assertContains("Undefined class 'Doctrine\\ORM\\Mapping'", $after);
self::assertSame(1, preg_match("/^Undefined class '([^']+)'$/", $after[0]));
// composer require doctrine/orm: it clears
$this->install($ws, true, 30);
$ide->emit('run.exit', ['id' => 2, 'code' => 0]);
$this->settle($ide);
self::assertSame([], $this->messages($ide, $alias));
}
public function testTheBuiltInMapComesFirstAndTheLongestPrefixWins(): void
{
$names = fn (string $ns) => array_column(PackageCandidates::known($ns), 'package');
self::assertSame(['doctrine/orm', 'symfony/orm-pack'], $names('Doctrine\\ORM\\Mapping'));
self::assertSame(['doctrine/collections', 'doctrine/common'], $names('Doctrine\\Common\\Collections\\ArrayCollection'));
self::assertSame(['symfony/http-foundation'], $names('Symfony\\Component\\HttpFoundation\\Request'));
self::assertSame(['symfony/security-bundle'], $names('Symfony\\Bundle\\SecurityBundle\\SecurityBundle'));
self::assertSame(['lexik/jwt-authentication-bundle'], $names('Lexik\\Bundle\\JWTAuthenticationBundle\\Services\\JWTTokenManagerInterface'));
self::assertSame(['phpunit/phpunit'], $names('PHPUnit\\Framework\\TestCase'));
self::assertTrue(PackageCandidates::known('PHPUnit\\Framework\\TestCase')[0]['dev']);
self::assertSame([], $names('Acme\\Unknown\\Thing'));
}
public function testPackagistResultsFollowTheKnownOnesOwnVendorFirst(): void
{
$urls = [];
$fetch = function (string $url) use (&$urls): Deferred {
$urls[] = $url;
return Deferred::resolved([200, json_encode(['total' => 3, 'results' => [
['name' => 'other/acme-thing', 'description' => 'Another', 'downloads' => 9000, 'url' => 'https://packagist.org/packages/other/acme-thing'],
['name' => 'acme/thing-bundle', 'description' => 'The one', 'downloads' => 10, 'url' => 'https://packagist.org/packages/acme/thing-bundle'],
['name' => 'acme/old', 'description' => 'Old', 'downloads' => 99999, 'abandoned' => true],
]])]);
};
$result = null;
(new PackageCandidates(new Packagist($fetch)))->find('Acme\\Thing\\Service')->then(function ($r) use (&$result) { $result = $r; });
self::assertSame(['acme/thing-bundle', 'other/acme-thing'], array_column($result, 'package'));
self::assertSame('packagist', $result[0]['source']);
self::assertStringContainsString('q=acme+thing', $urls[0]);
$known = null;
(new PackageCandidates(new Packagist($fetch)))->find('Doctrine\\ORM\\Mapping')->then(function ($r) use (&$known) { $known = $r; });
self::assertSame('doctrine/orm', $known[0]['package'], 'the built-in map is first');
self::assertSame('known', $known[0]['source']);
}
public function testAFailingPackagistLeavesTheKnownCandidates(): void
{
$result = null;
$fail = fn (string $url) => Deferred::rejected(new \RuntimeException('offline'));
(new PackageCandidates(new Packagist($fail)))->find('Twig\\Environment')->then(function ($r) use (&$result) { $result = $r; });
self::assertSame(['twig/twig'], array_column($result, 'package'));
}
public function testApiPlatformIsInstalledWithThePackageOfTheSymfonyVersion(): void
{
$plan = function (array $composer, ?array $lock = null) {
$ws = sys_get_temp_dir() . '/jumphp-plan-' . bin2hex(random_bytes(4));
mkdir($ws);
file_put_contents("$ws/composer.json", json_encode($composer));
if ($lock !== null) {
file_put_contents("$ws/composer.lock", json_encode(['packages' => $lock]));
}
$p = ApiInstall::plan($ws);
exec('rm -rf ' . escapeshellarg($ws));
return $p;
};
$flex = ['symfony/flex' => '^2', 'symfony/framework-bundle' => '7.1.*'];
$p = $plan(['require' => $flex]);
self::assertSame(['api', 'composer require api', false], [$p['package'], $p['command'], $p['installed']]);
self::assertSame('7.1', $p['symfony']);
// the lock wins over the constraint; no Flex: api-platform/symfony
$p = $plan(['require' => ['symfony/framework-bundle' => '^6.4']], [['name' => 'symfony/framework-bundle', 'version' => 'v7.2.3']]);
self::assertSame(['api-platform/symfony', '7.2'], [$p['package'], $p['symfony']]);
$p = $plan(['require' => ['symfony/framework-bundle' => '6.2.*', 'symfony/flex' => '^2']]);
self::assertSame(['api-platform/core', '^3.2', 'composer require api-platform/core:^3.2'], [$p['package'], $p['constraint'], $p['command']]);
$p = $plan(['require' => ['symfony/framework-bundle' => '^5.4']]);
self::assertSame(['api-platform/core', '^2.7'], [$p['package'], $p['constraint']]);
$p = $plan(['require' => $flex + ['api-platform/core' => '^4.0']]);
self::assertTrue($p['installed']);
// the JWT bundle
$ws = $this->dir;
file_put_contents("$ws/composer.json", '{"require": {}}');
$jwt = ApiInstall::plan($ws, 'jwt');
self::assertSame(['lexik/jwt-authentication-bundle', false], [$jwt['package'], $jwt['installed']]);
}
public function testTheFlexAliasIsAcceptedByComposerRequire(): void
{
self::assertSame(['require', 'api', '--no-interaction'], ComposerProject::arguments(['action' => 'require', 'package' => 'api']));
$this->expectException(\InvalidArgumentException::class);
ComposerProject::arguments(['action' => 'require', 'package' => 'not a name']);
}
public function testTheIdeAnswersThePlanAndEnablesTheWindowWithoutRestart(): void
{
$ws = new LocalWorkspace($this->dir);
$ws->write('composer.json', '{"require": {"symfony/framework-bundle": "7.1.*", "symfony/flex": "^2"}}');
$ide = new Ide($ws, null, fn () => null);
self::assertArrayNotHasKey('apiplatform', $ide->capabilities);
self::assertFalse($ide->has('apiplatform.classes'));
$plan = $ide->handle('apiplatform.install.plan', []);
self::assertSame('api', $plan['package']);
self::assertFalse($ide->handle('apiplatform.enable', [])['enabled']);
// composer require api ran: the next enable registers the window's commands
$ws->write('composer.json', '{"require": {"symfony/flex": "^2", "api-platform/symfony": "^4"}}');
self::assertTrue($ide->handle('apiplatform.enable', [])['enabled']);
self::assertTrue($ide->has('apiplatform.classes'));
self::assertTrue($ide->capabilities['apiplatform']);
}
}