rob-revisited/ide/tests/CommandWizardTest.php

562 lines
35 KiB
PHP

<?php
namespace JumPHP\Ide\Tests;
use JumPHP\Ide\Async\Deferred;
use JumPHP\Ide\Async\Processes;
use JumPHP\Ide\Scripts\Castor;
use JumPHP\Ide\Scripts\TaskDetector;
use JumPHP\Ide\Wizard\CastorTask;
use JumPHP\Ide\Wizard\Code;
use JumPHP\Ide\Wizard\SymfonyCommand;
use JumPHP\Ide\Wizard\WizardCommands;
use PHPUnit\Framework\TestCase;
/**
* The command wizards (ide/src/Wizard): a Symfony console command and a Castor task written from a model, read back
* into it, and edited in place with the rest of the file left byte for byte.
*/
final class CommandWizardTest extends TestCase
{
private string $dir;
protected function setUp(): void
{
$this->dir = sys_get_temp_dir() . '/jumphp-wizard-' . bin2hex(random_bytes(4));
mkdir($this->dir, 0777, true);
}
protected function tearDown(): void
{
exec('rm -rf ' . escapeshellarg($this->dir));
}
/** @return array<string, mixed> */
private function report(): array
{
return ['name' => 'app:send-report', 'description' => 'Sends the report', 'aliases' => 'report', 'namespace' => 'App\\Command',
'arguments' => [['name' => 'user', 'mode' => 'required', 'description' => 'The user'], ['name' => 'months', 'mode' => 'optional', 'type' => 'int', 'default' => '3']],
'options' => [['name' => 'dry-run', 'mode' => 'none', 'description' => 'Change nothing'], ['name' => 'format', 'shortcut' => 'f', 'mode' => 'required', 'default' => 'pdf'],
['name' => 'tag', 'mode' => 'array'], ['name' => 'color', 'mode' => 'negatable'], ['name' => 'limit', 'mode' => 'optional', 'type' => 'int']],
'services' => [['class' => 'App\\Repository\\UserRepository'], ['class' => 'Psr\\Log\\LoggerInterface']],
'body' => [['type' => 'title', 'text' => 'Report'], ['type' => 'confirm', 'var' => 'go', 'question' => 'Send it?', 'default' => false],
['type' => 'table', 'headers' => 'Id, Name', 'rows' => "1, Ada\n2, Alan"], ['type' => 'success', 'text' => 'Sent.']]];
}
public function testACommandIsWrittenInTheAttributesStyleOfSymfony73(): void
{
self::assertSame(file_get_contents(__DIR__ . '/fixtures/wizard/send-report-attributes.php'), SymfonyCommand::generate(['style' => 'attributes'] + $this->report()));
}
public function testACommandIsWrittenInTheClassicStyleWithConfigureAndExecute(): void
{
self::assertSame(file_get_contents(__DIR__ . '/fixtures/wizard/send-report-classic.php'), SymfonyCommand::generate(['style' => 'classic'] + $this->report()));
}
public function testASmallCommandHasItsQuestionsAProgressBarAndItsResult(): void
{
$code = SymfonyCommand::generate(['name' => 'app:hello', 'namespace' => 'App\\Command', 'result' => 'FAILURE', 'body' => [
['type' => 'ask', 'var' => 'who', 'question' => 'Your name?', 'default' => 'World'],
['type' => 'choice', 'var' => 'tone', 'question' => 'Tone?', 'choices' => 'warm, cold', 'default' => 'warm'],
['type' => 'progress', 'count' => 3], ['type' => 'success', 'text' => 'Hello!']]]);
self::assertSame(<<<'PHP'
<?php
namespace App\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'app:hello',
)]
final class HelloCommand
{
public function __invoke(SymfonyStyle $io): int
{
$who = $io->ask('Your name?', 'World');
$tone = $io->choice('Tone?', ['warm', 'cold'], 'warm');
$io->progressStart(3);
for ($i = 0; $i < 3; ++$i) {
// one step of the work
$io->progressAdvance();
}
$io->progressFinish();
$io->success('Hello!');
return Command::FAILURE;
}
}
PHP, $code);
// classic and hidden, its help in setHelp() (the help: of #[AsCommand] needs Symfony 7.3)
$classic = SymfonyCommand::generate(['style' => 'classic', 'name' => 'app:hello', 'namespace' => 'App\\Command', 'hidden' => true, 'help' => 'Says hello.']);
self::assertStringContainsString(" name: 'app:hello',\n hidden: true,\n)]\nfinal class HelloCommand extends Command", $classic);
self::assertStringContainsString(" \$this\n ->setHelp('Says hello.')\n ;", $classic);
}
public function testBadNamesAreRefused(): void
{
$this->expectException(\InvalidArgumentException::class);
SymfonyCommand::generate(['name' => 'app:x', 'arguments' => [['name' => 'a'], ['name' => 'a']]]);
}
public function testTheStyleFollowsTheProjectsSymfonyConsole(): void
{
$lock = fn (string $v) => file_put_contents("$this->dir/composer.lock", json_encode(['packages' => [['name' => 'symfony/console', 'version' => $v]]]));
$lock('v8.1.11');
self::assertSame(['version' => '8.1.11', 'invokable' => true, 'style' => 'attributes'], SymfonyCommand::support($this->dir));
$lock('v7.3.0');
self::assertSame('attributes', SymfonyCommand::support($this->dir)['style']);
$lock('v7.2.9');
self::assertSame('classic', SymfonyCommand::support($this->dir)['style']);
$lock('v6.4.20');
self::assertSame('classic', SymfonyCommand::support($this->dir)['style']);
file_put_contents("$this->dir/composer.json", json_encode(['autoload' => ['psr-4' => ['App\\' => 'src/']]]));
self::assertSame('App\\Command', SymfonyCommand::namespaceFor($this->dir, 'src/Command'));
self::assertSame('App\\Console\\Admin', SymfonyCommand::namespaceFor($this->dir, 'src/Console/Admin'));
self::assertSame('SendReportCommand', SymfonyCommand::className('app:send-report'));
}
public function testBothStylesAreReadBackIntoTheSameModel(): void
{
$meaning = static function (array $m): array {
unset($m['style'], $m['body']);
foreach (['arguments', 'options'] as $k) {
// the classic style has no PHP types: an int default reads as int, an empty one as a string
$m[$k] = array_map(fn ($e) => array_diff_key($e, ['original' => 1, 'type' => 1]), $m[$k]);
}
return $m;
};
$attributes = SymfonyCommand::read(SymfonyCommand::generate(['style' => 'attributes'] + $this->report()));
$classic = SymfonyCommand::read(SymfonyCommand::generate(['style' => 'classic'] + $this->report()));
self::assertSame('attributes', $attributes['style']);
self::assertSame('classic', $classic['style']);
self::assertSame($meaning($attributes), $meaning($classic));
self::assertSame(['report'], $attributes['aliases']);
self::assertSame(['user', 'months'], array_column($attributes['arguments'], 'name'));
self::assertSame(['none', 'required', 'array', 'negatable', 'optional'], array_column($attributes['options'], 'mode'));
self::assertSame(['App\\Repository\\UserRepository', 'Psr\\Log\\LoggerInterface'], array_column($attributes['services'], 'class'));
self::assertSame(['3', 'int'], [$attributes['arguments'][1]['default'], $attributes['arguments'][1]['type']]);
self::assertSame(['f', 'pdf'], [$attributes['options'][1]['shortcut'], $attributes['options'][1]['default']]);
}
public function testOlderFormsAreReadToo(): void
{
$old = <<<'PHP'
<?php
namespace App\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
#[AsCommand('app:old|legacy|ancient')]
class OldCommand extends Command
{
protected function configure()
{
$this->setDescription('An old one');
$this->addArgument('path', InputArgument::IS_ARRAY | InputArgument::REQUIRED, 'Paths');
$this->addOption('level', 'l', InputOption::VALUE_OPTIONAL, 'Level', 2);
}
}
PHP;
$m = SymfonyCommand::read($old);
self::assertSame(['app:old', ['legacy', 'ancient'], 'An old one', 'classic'], [$m['name'], $m['aliases'], $m['description'], $m['style']]);
self::assertSame(['path', 'required', true], [$m['arguments'][0]['name'], $m['arguments'][0]['mode'], $m['arguments'][0]['array']]);
self::assertSame(['level', 'l', 'optional'], [$m['options'][0]['name'], $m['options'][0]['shortcut'], $m['options'][0]['mode']]);
// edited: the pipe form kept, setDescription() changed where it is, the rest byte for byte
$m['aliases'] = ['legacy'];
$m['description'] = 'Still old';
$m['arguments'][0]['description'] = 'The paths';
$edited = SymfonyCommand::edit($old, $m);
self::assertSame(['-' => [
"#[AsCommand('app:old|legacy|ancient')]",
" \$this->setDescription('An old one');",
" \$this->addArgument('path', InputArgument::IS_ARRAY | InputArgument::REQUIRED, 'Paths');",
], '+' => [
"#[AsCommand('app:old|legacy')]",
" \$this->setDescription('Still old');",
" \$this->addArgument('path', InputArgument::REQUIRED | InputArgument::IS_ARRAY, 'The paths');",
]], Code::changedLines($old, $edited));
}
public function testAnUnchangedModelLeavesTheFileByteForByte(): void
{
foreach (['attributes', 'classic'] as $style) {
$code = SymfonyCommand::generate(['style' => $style] + $this->report());
// a hand-made touch the wizard knows nothing about
$code = str_replace(" public function __construct(", " // the repository of users\n public function __construct(", $code);
self::assertSame($code, SymfonyCommand::edit($code, SymfonyCommand::read($code)), $style);
}
}
public function testAnEditRewritesOnlyWhatChangedInTheAttributesStyle(): void
{
$code = SymfonyCommand::generate(['style' => 'attributes'] + $this->report());
$code = str_replace(" \$io->success('Sent.');", " \$io->success('Sent to ' . \$user . '.');", $code);
$m = SymfonyCommand::read($code);
$m['description'] = 'Sends it';
$m['hidden'] = true;
$m['arguments'][0]['name'] = 'who'; // renamed: its variable follows in the body
$m['arguments'][] = ['name' => 'extra', 'mode' => 'optional'];
$m['options'][1]['default'] = 'csv';
unset($m['options'][2]); // --tag removed
$m['options'][] = ['name' => 'force', 'mode' => 'none', 'description' => 'No questions'];
$edited = SymfonyCommand::edit($code, $m);
self::assertSame(['-' => [
" description: 'Sends the report',",
" #[Argument('The user')] string \$user,",
" #[Option(shortcut: 'f')] string \$format = 'pdf',",
" #[Option] array \$tag = [],",
" \$io->success('Sent to ' . \$user . '.');",
], '+' => [
" description: 'Sends it',",
' hidden: true,',
" #[Argument('The user')] string \$who,",
" #[Argument] ?string \$extra = null,",
" #[Option(shortcut: 'f')] string \$format = 'csv',",
" #[Option('No questions')] bool \$force = false,",
" \$io->success('Sent to ' . \$who . '.');",
]], Code::changedLines($code, $edited));
self::assertStringContainsString(" #[Argument] int \$months = 3,\n #[Argument] ?string \$extra = null,\n #[Option('Change nothing')]", $edited);
self::assertStringContainsString(" #[Option] int|bool \$limit = false,\n #[Option('No questions')] bool \$force = false,\n ): int {", $edited);
self::assertNotFalse(@token_get_all($edited));
}
public function testAnEditRewritesOnlyWhatChangedInTheClassicStyle(): void
{
$code = SymfonyCommand::generate(['style' => 'classic'] + $this->report());
$m = SymfonyCommand::read($code);
$m['arguments'][0]['name'] = 'who';
$m['arguments'][] = ['name' => 'extra', 'mode' => 'optional', 'description' => 'More'];
unset($m['options'][2]);
$m['options'][] = ['name' => 'force', 'shortcut' => 'F', 'mode' => 'none'];
$m['services'][] = ['class' => 'App\\Mailer\\ReportMailer'];
$edited = SymfonyCommand::edit($code, $m);
self::assertSame(['-' => [
" ->addArgument('user', InputArgument::REQUIRED, 'The user')",
" ->addOption('tag', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY)",
" \$user = \$input->getArgument('user');",
" \$tag = \$input->getOption('tag');",
], '+' => [
'use App\\Mailer\\ReportMailer;',
' private readonly ReportMailer $reportMailer,',
" ->addArgument('who', InputArgument::REQUIRED, 'The user')",
" ->addArgument('extra', InputArgument::OPTIONAL, 'More')",
" ->addOption('force', 'F', InputOption::VALUE_NONE)",
" \$who = \$input->getArgument('who');",
]], Code::changedLines($code, $edited));
self::assertStringContainsString(" ->addArgument('months', InputArgument::OPTIONAL, '', 3)\n ->addArgument('extra', InputArgument::OPTIONAL, 'More')\n ->addOption('dry-run'", $edited);
}
public function testArgumentsAreAddedToACommandThatHadNone(): void
{
$code = SymfonyCommand::generate(['style' => 'classic', 'name' => 'app:hello', 'namespace' => 'App\\Command']);
$m = SymfonyCommand::read($code);
$m['arguments'] = [['name' => 'who', 'mode' => 'required']];
$edited = SymfonyCommand::edit($code, $m);
self::assertStringContainsString(" protected function configure(): void\n {\n \$this\n ->addArgument('who', InputArgument::REQUIRED)\n ;\n }\n\n protected function execute(", $edited);
self::assertStringContainsString("use Symfony\\Component\\Console\\Input\\InputArgument;\nuse Symfony\\Component\\Console\\Input\\InputInterface;", $edited);
$invokable = SymfonyCommand::generate(['name' => 'app:hello', 'namespace' => 'App\\Command']);
$m = SymfonyCommand::read($invokable);
$m['options'] = [['name' => 'yell', 'mode' => 'none']];
$edited = SymfonyCommand::edit($invokable, $m);
self::assertStringContainsString('public function __invoke(SymfonyStyle $io, #[Option] bool $yell = false): int', $edited);
self::assertStringContainsString("use Symfony\\Component\\Console\\Attribute\\AsCommand;\nuse Symfony\\Component\\Console\\Attribute\\Option;\nuse Symfony\\Component\\Console\\Command\\Command;", $edited);
}
public function testTheRunFormMakesTheCommandLine(): void
{
$m = SymfonyCommand::normalize(['style' => 'attributes'] + $this->report());
self::assertSame(['app:send-report', '--dry-run', '--format=csv', '--tag=a', '--tag=b', 'ada'],
SymfonyCommand::argv($m, ['arguments' => ['user' => 'ada'], 'options' => ['dry-run' => true, 'format' => 'csv', 'tag' => 'a b']]));
}
// Castor ---------------------------------------------------------------------------------------------------------
/** @return array<string, mixed> */
private function reset(): array
{
return ['name' => 'db:reset', 'description' => 'Resets the database', 'aliases' => 'dbr',
'params' => [['kind' => 'argument', 'name' => 'env', 'description' => 'The environment'], ['kind' => 'option', 'name' => 'force', 'type' => 'bool', 'shortcut' => 'f'],
['kind' => 'option', 'name' => 'seed', 'type' => 'int', 'default' => '3'], ['kind' => 'option', 'name' => 'only', 'mode' => 'array', 'description' => 'Tables']],
'body' => [['type' => 'title', 'text' => 'Reset'], ['type' => 'run', 'command' => 'bin/console doctrine:database:drop --force', 'cwd' => 'app', 'env' => 'APP_ENV=test', 'tty' => true],
['type' => 'run', 'command' => 'bin/console cache:clear', 'allowFailure' => true], ['type' => 'capture', 'var' => 'rev', 'command' => 'git rev-parse HEAD'],
['type' => 'fs', 'op' => 'mkdir', 'path' => 'var/cache'], ['type' => 'http', 'url' => 'https://example.org/ping'], ['type' => 'notify', 'text' => 'Done']]];
}
public function testACastorTaskIsWrittenWithItsAttributesAndHelpers(): void
{
$file = CastorTask::write($this->dir, $this->reset())[0];
self::assertSame('castor.php', $file['file']);
self::assertNull($file['before']);
self::assertSame(<<<'PHP'
<?php
use Castor\Attribute\AsArgument;
use Castor\Attribute\AsOption;
use Castor\Attribute\AsTask;
use Symfony\Component\Console\Input\InputOption;
use function Castor\capture;
use function Castor\context;
use function Castor\fs;
use function Castor\http_request;
use function Castor\io;
use function Castor\notify;
use function Castor\run;
#[AsTask(name: 'reset', namespace: 'db', description: 'Resets the database', aliases: ['dbr'])]
function dbReset(
#[AsArgument(description: 'The environment')] string $env,
#[AsOption(shortcut: 'f')] bool $force = false,
int $seed = 3,
#[AsOption(mode: InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, description: 'Tables')] array $only = [],
): void {
io()->title('Reset');
run('bin/console doctrine:database:drop --force', context: context()
->withWorkingDirectory('app')
->withEnvironment(['APP_ENV' => 'test'])
->withTty());
run('bin/console cache:clear', context: context()->withAllowFailure());
$rev = capture('git rev-parse HEAD');
fs()->mkdir('var/cache');
$response = http_request('GET', 'https://example.org/ping');
io()->writeln($response->getContent());
notify('Done');
}
PHP, $file['after']);
self::assertSame(['db:reset'], array_column(TaskDetector::castorStatic([$file['after']]), 'name'));
}
public function testAContextAndAListenerAreWritten(): void
{
[$context, $uses] = CastorTask::generate(['kind' => 'context', 'context' => ['name' => 'prod', 'default' => true, 'workingDirectory' => 'app', 'env' => 'APP_ENV=prod', 'tty' => true, 'timeout' => 120]]);
self::assertSame("#[AsContext(name: 'prod', default: true)]\nfunction prodContext(): Context\n{\n return (new Context())\n ->withWorkingDirectory('app')\n"
. " ->withEnvironment(['APP_ENV' => 'prod'])\n ->withTty()\n ->withTimeout(120);\n}\n", $context);
self::assertSame(['Castor\\Attribute\\AsContext', 'Castor\\Context'], $uses);
[$listener, $uses] = CastorTask::generate(['kind' => 'listener', 'listener' => ['event' => 'AfterExecuteTaskEvent', 'priority' => 5], 'body' => [['type' => 'note', 'text' => 'done']]]);
self::assertSame("#[AsListener(event: AfterExecuteTaskEvent::class, priority: 5)]\nfunction onAfterExecuteTask(AfterExecuteTaskEvent \$event): void\n{\n io()->note('done');\n}\n", $listener);
self::assertContains('Castor\\Event\\AfterExecuteTaskEvent', $uses);
}
public function testATaskInADotCastorFileIsImportedByTheRootFile(): void
{
file_put_contents("$this->dir/castor.php", "<?php\n\nuse Castor\\Attribute\\AsTask;\n\nuse function Castor\\run;\n\n#[AsTask]\nfunction build(): void\n{\n run('make');\n}\n");
$changes = CastorTask::write($this->dir, ['name' => 'deploy', 'file' => '.castor/deploy.php', 'body' => [['type' => 'run', 'command' => 'rsync -a dist/ server:']]]);
self::assertSame(['.castor/deploy.php', 'castor.php'], array_column($changes, 'file'));
self::assertSame("<?php\n\nuse Castor\\Attribute\\AsTask;\n\nuse function Castor\\run;\n\n#[AsTask]\nfunction deploy(): void\n{\n run('rsync -a dist/ server:');\n}\n", $changes[0]['after']);
self::assertSame("<?php\n\nuse Castor\\Attribute\\AsTask;\n\nuse function Castor\\import;\nuse function Castor\\run;\n\nimport(__DIR__ . '/.castor/deploy.php');\n\n#[AsTask]\nfunction build(): void\n{\n run('make');\n}\n", $changes[1]['after']);
// a root file that imports the whole folder is left alone
self::assertSame("<?php\nimport(__DIR__ . '/.castor');\n", Castor::ensureImport("<?php\nimport(__DIR__ . '/.castor');\n", '/.castor/deploy.php'));
// a function name already taken in another Castor file
mkdir("$this->dir/.castor");
file_put_contents("$this->dir/.castor/deploy.php", $changes[0]['after']);
$this->expectException(\InvalidArgumentException::class);
CastorTask::write($this->dir, ['name' => 'deploy']);
}
public function testATaskIsReadBackAndAnUnchangedOneIsLeftAlone(): void
{
$file = CastorTask::write($this->dir, $this->reset())[0]['after'];
$m = CastorTask::readTask($file, 'db:reset');
self::assertSame(['dbReset', 'reset', 'db', 'Resets the database', ['dbr']], [$m['function'], $m['name'], $m['namespace'], $m['description'], $m['aliases']]);
self::assertSame([['argument', 'env', 'required'], ['option', 'force', 'auto'], ['option', 'seed', 'auto'], ['option', 'only', 'array']],
array_map(fn ($p) => [$p['kind'], $p['name'], $p['mode']], $m['params']));
self::assertSame(['f', '3', 'int'], [$m['params'][1]['shortcut'], $m['params'][2]['default'], $m['params'][2]['type']]);
self::assertSame($file, CastorTask::edit($file, 'dbReset', $m));
// the existing Castor support reads the same
self::assertSame([['name' => 'db:reset', 'help' => 'Resets the database', 'aliases' => ['dbr']]], TaskDetector::castorStatic([$file]));
}
public function testAnEditOfATaskRewritesOnlyWhatChanged(): void
{
$file = CastorTask::write($this->dir, $this->reset())[0]['after'];
$file = str_replace("#[AsTask(name: 'reset'", "// builds everything\n#[AsTask]\nfunction hello(): void\n{\n run('echo hi');\n}\n\n#[AsTask(name: 'reset'", $file);
$m = CastorTask::readTask($file, 'dbReset');
$m['params'][0]['name'] = 'environment'; // renamed: $env follows
$m['params'][1]['description'] = 'Really';
unset($m['params'][2]); // --seed removed
$m['params'][] = ['kind' => 'argument', 'name' => 'target', 'mode' => 'optional', 'default' => 'all'];
$m['params'][] = ['kind' => 'option', 'name' => 'dry-run', 'type' => 'bool'];
$m['description'] = '';
$m['function'] = 'resetAll';
$m['name'] = 'reset-all';
$file = str_replace("io()->title('Reset');", "io()->title('Reset ' . \$env);", $file);
$edited = CastorTask::edit($file, 'dbReset', $m);
self::assertSame(['-' => [
"#[AsTask(name: 'reset', namespace: 'db', description: 'Resets the database', aliases: ['dbr'])]",
'function dbReset(',
" #[AsArgument(description: 'The environment')] string \$env,",
" #[AsOption(shortcut: 'f')] bool \$force = false,",
' int $seed = 3,',
" io()->title('Reset ' . \$env);",
], '+' => [
"#[AsTask(namespace: 'db', aliases: ['dbr'])]",
'function resetAll(',
" #[AsArgument(description: 'The environment')] string \$environment,",
" #[AsArgument] string \$target = 'all',",
" #[AsOption(shortcut: 'f', description: 'Really')] bool \$force = false,",
' bool $dryRun = false,',
" io()->title('Reset ' . \$environment);",
]], Code::changedLines($file, $edited));
self::assertStringStartsWith("<?php\n\nuse Castor\\Attribute\\AsArgument;", $edited);
self::assertStringContainsString("// builds everything\n#[AsTask]\nfunction hello(): void\n{\n run('echo hi');\n}\n", $edited);
// a task without arguments gets its first one and a description
$hello = CastorTask::readTask($edited, 'hello');
$hello['params'] = [['kind' => 'argument', 'name' => 'who']];
$hello['description'] = 'Says hi';
self::assertStringContainsString("#[AsTask(description: 'Says hi')]\nfunction hello(string \$who): void\n", CastorTask::edit($edited, 'hello', $hello));
self::assertSame(['db:reset-all', 'hello'], array_column(TaskDetector::castorStatic([$edited]), 'name'));
}
public function testTheCastorRunFormMakesTheCommandLine(): void
{
self::assertSame(['db:reset', '--force', '--seed=5', '--only=a', '--only=b', 'prod'],
CastorTask::argv($this->reset(), ['arguments' => ['env' => 'prod'], 'options' => ['force' => true, 'seed' => '5', 'only' => 'a b']]));
}
// the commands of the window -------------------------------------------------------------------------------------
public function testThePreviewIsAppliedOnlyWhenTheFileDidNotChange(): void
{
file_put_contents("$this->dir/composer.json", json_encode(['autoload' => ['psr-4' => ['App\\' => 'src/']]]));
$h = [];
WizardCommands::register(function (string $name, callable $handler) use (&$h): void {
$h[$name] = $handler;
}, $this->dir);
$preview = $h['wizard.symfonyPreview'](['model' => ['name' => 'app:greet', 'description' => 'Greets']]);
self::assertSame('src/Command/GreetCommand.php', $preview['changes'][0]['file']);
self::assertStringContainsString("namespace App\\Command;", $preview['changes'][0]['after']);
self::assertSame(['files' => ['src/Command/GreetCommand.php']], $h['wizard.apply']($preview));
self::assertSame('src/Command/GreetCommand.php', $h['wizard.symfonyRead'](['name' => 'app:greet'])['file']);
// an edit previewed, the file changed meanwhile: refused
$read = $h['wizard.symfonyRead'](['file' => 'src/Command/GreetCommand.php']);
$edit = $h['wizard.symfonyPreview'](['file' => $read['file'], 'model' => ['description' => 'Says hello'] + $read['model']]);
file_put_contents("$this->dir/src/Command/GreetCommand.php", "// touched\n", FILE_APPEND);
try {
$h['wizard.apply']($edit);
self::fail('a changed file was overwritten');
} catch (\RuntimeException) {
self::assertStringEndsWith("// touched\n", (string)file_get_contents("$this->dir/src/Command/GreetCommand.php"));
}
self::assertSame('php bin/console app:greet --yell', $h['wizard.symfonyArgv'](['model' => ['name' => 'app:greet', 'options' => [['name' => 'yell', 'mode' => 'none']]],
'values' => ['options' => ['yell' => true]]])['line']);
// Castor: written, listed, read back
$h['wizard.apply']($h['wizard.castorPreview'](['model' => $this->reset()]));
self::assertSame([['file' => 'castor.php', 'kind' => 'task', 'function' => 'dbReset', 'name' => 'reset', 'namespace' => 'db', 'description' => 'Resets the database']],
$h['wizard.castorList']([])['items']);
self::assertSame('castor.php', $h['wizard.castorRead'](['name' => 'db:reset'])['file']);
$this->expectException(\InvalidArgumentException::class);
$h['wizard.apply'](['changes' => [['file' => '../escape.php', 'before' => null, 'after' => 'x']]]);
}
public function testTheRunFormsArgumentsReachTheScriptsRunnerQuoted(): void
{
mkdir("$this->dir/project");
file_put_contents("$this->dir/project/Makefile", "hello:\n\techo hi\n");
$trust = new \JumPHP\Ide\Scripts\ScriptTrust("$this->dir/trusted.json");
$trust->trust("$this->dir/project");
$h = [];
$processes = new Processes();
\JumPHP\Ide\Scripts\ScriptCommands::register(function (string $name, callable $handler) use (&$h): void {
$h[$name] = $handler;
}, $processes, "$this->dir/project", fn () => false, $trust, "$this->dir/home");
$prepared = $h['scripts.prepare'](['ref' => 'make:hello', 'args' => ['--name=Ada', "it's"]]);
$prepared = $prepared instanceof Deferred ? $processes->wait($prepared, 30) : $prepared;
self::assertSame("make hello --name=Ada 'it'\\''s'", $prepared['command']);
}
// real programs ---------------------------------------------------------------------------------------------------
/** castor itself (its phar, run by the php of this image): the generated tasks are listed and run with their arguments */
public function testARealCastorListsAndRunsTheGeneratedTasks(): void
{
$phar = sys_get_temp_dir() . '/jumphp-castor-test.phar';
if (!is_file($phar) || filesize($phar) < 100000) {
$data = @file_get_contents('https://github.com/jolicode/castor/releases/latest/download/castor.linux-amd64.phar', false,
stream_context_create(['http' => ['timeout' => 20, 'user_agent' => 'JumPHP-IDE']]));
if (!is_string($data) || strlen($data) < 100000) {
self::markTestSkipped('the castor phar could not be fetched');
}
file_put_contents($phar, $data);
}
$apply = function (array $changes): void {
foreach ($changes as $c) {
@mkdir(dirname("$this->dir/{$c['file']}"), 0777, true);
file_put_contents("$this->dir/{$c['file']}", $c['after']);
}
};
$apply(CastorTask::write($this->dir, ['name' => 'greet', 'description' => 'Greets someone',
'params' => [['kind' => 'argument', 'name' => 'who', 'description' => 'Who'], ['kind' => 'option', 'name' => 'times', 'type' => 'int', 'default' => '1'],
['kind' => 'option', 'name' => 'yell', 'type' => 'bool', 'shortcut' => 'y']],
'body' => [['type' => 'code', 'code' => "for (\$i = 0; \$i < \$times; \$i++) {\n io()->writeln(\$yell ? strtoupper('hello ' . \$who) : 'hello ' . \$who);\n}"],
['type' => 'run', 'command' => 'echo ran in $PWD', 'cwd' => 'sub', 'env' => 'X=1']]]));
mkdir("$this->dir/sub");
$apply(CastorTask::write($this->dir, ['name' => 'ops:deploy', 'file' => '.castor/ops.php', 'body' => [['type' => 'success', 'text' => 'deployed']]]));
$apply(CastorTask::write($this->dir, ['kind' => 'context', 'context' => ['name' => 'ci', 'env' => 'CI=1']]));
$castor = function (string $args) use ($phar): array {
exec('cd ' . escapeshellarg($this->dir) . ' && php ' . escapeshellarg($phar) . " $args 2>&1", $out, $code);
return [null, $out, $code];
};
[, $out, $code] = $castor('list --format=json --no-ansi');
$json = json_decode(substr(implode("\n", $out), (int)strpos(implode("\n", $out), '{')), true);
if (!is_array($json)) {
self::markTestSkipped('castor list did not answer here: ' . implode("\n", array_slice($out, -5)));
}
self::assertSame(['greet', 'ops:deploy'], array_values(array_filter(array_column($json['commands'], 'name'), fn ($n) => in_array($n, ['greet', 'ops:deploy'], true))));
[, $out, $code] = $castor('greet Ada --times=2 -y --no-ansi');
self::assertSame(0, $code, implode("\n", $out));
self::assertSame(2, substr_count(implode("\n", $out), 'HELLO ADA'));
self::assertStringContainsString("ran in $this->dir/sub", implode("\n", $out));
[, $out, $code] = $castor('ops:deploy --no-ansi');
self::assertSame(0, $code, implode("\n", $out));
self::assertStringContainsString('deployed', implode("\n", $out));
}
/**
* A real Symfony project (JUMPHP_WIZARD_SYMFONY: a copy of one, its vendor/ installed): the generated commands of
* both styles are listed by bin/console and run with the run form's command line.
*/
public function testARealSymfonyProjectListsAndRunsTheGeneratedCommands(): void
{
$project = (string)getenv('JUMPHP_WIZARD_SYMFONY');
if ($project === '' || !is_file("$project/bin/console")) {
self::markTestSkipped('JUMPHP_WIZARD_SYMFONY is not a Symfony project');
}
$style = SymfonyCommand::support($project)['style'];
$made = [];
foreach (['attributes', 'classic'] as $s) {
if ($s === 'attributes' && $style !== 'attributes') {
continue;
}
$m = ['style' => $s, 'name' => "wizard:$s", 'class' => 'Wizard' . ucfirst($s) . 'Command', 'description' => "Made by the wizard ($s)",
'namespace' => SymfonyCommand::namespaceFor($project, 'src/Command'),
'arguments' => [['name' => 'who', 'mode' => 'required']], 'options' => [['name' => 'times', 'mode' => 'required', 'type' => 'int', 'default' => '1'], ['name' => 'yell', 'mode' => 'none']],
'body' => [['type' => 'title', 'text' => "Wizard $s"], ['type' => 'code', 'code' => "\$io->writeln('greeting ' . \$who);"], ['type' => 'success', 'text' => 'done']]];
@mkdir("$project/src/Command", 0777, true);
file_put_contents($made[] = "$project/src/Command/{$m['class']}.php", SymfonyCommand::generate($m));
}
try {
exec('cd ' . escapeshellarg($project) . ' && php bin/console list --format=json 2>&1', $out, $code);
self::assertSame(0, $code, implode("\n", array_slice($out, -10)));
$names = array_column(json_decode(implode("\n", $out), true)['commands'] ?? [], 'name');
foreach ($made as $file) {
$m = SymfonyCommand::read((string)file_get_contents($file));
self::assertContains($m['name'], $names);
$argv = SymfonyCommand::argv($m, ['arguments' => ['who' => 'Ada'], 'options' => ['yell' => true, 'times' => '2']]);
$out = [];
exec('cd ' . escapeshellarg($project) . ' && php bin/console ' . implode(' ', array_map('escapeshellarg', $argv)) . ' --no-interaction 2>&1', $out, $code);
self::assertSame(0, $code, implode("\n", $out));
self::assertStringContainsString('greeting Ada', implode("\n", $out));
}
} finally {
array_map('unlink', $made);
}
}
}