通用代码生成器基类

Testing Is Documentation

tests/Console/MakeTest.php通用代码生成器基类 - 图1

在项目实际开发中经常需要生成一个基础模板,QueryPHP 对这一场景进行了封装,提供了一个基础的代码生成器基类, 可以十分便捷地生成你需要的模板代码。

Uses

  1. <?php
  2. use Leevel\Console\Make;
  3. use Leevel\Filesystem\Helper;
  4. use Tests\Console\Command\MakeFile;
  5. use Tests\Console\Command\MakeFileWithGlobalReplace;

基本使用方法

fixture 定义

Tests\Console\Command\MakeFile

  1. namespace Tests\Console\Command;
  2. use Leevel\Console\Argument;
  3. use Leevel\Console\Make;
  4. class MakeFile extends Make
  5. {
  6. protected string $name = 'make:test';
  7. protected string $description = 'Create a test file.';
  8. public function handle(): int
  9. {
  10. $this->setTemplatePath(__DIR__.'/'.($this->getArgument('template') ?: 'template'));
  11. $this->setCustomReplaceKeyValue('key1', 'hello key1');
  12. $this->setCustomReplaceKeyValue('key2', 'hello key2');
  13. $this->setCustomReplaceKeyValue(['key3' => 'hello key3', 'key4' => 'hello key4']);
  14. $this->setSaveFilePath(__DIR__.'/'.$this->getArgument('cache').'/'.$this->getArgument('name'));
  15. $this->setMakeType('test');
  16. $this->create();
  17. return 0;
  18. }
  19. protected function getArguments(): array
  20. {
  21. return [
  22. [
  23. 'name',
  24. Argument::OPTIONAL,
  25. 'This is a name.',
  26. ],
  27. [
  28. 'template',
  29. Argument::OPTIONAL,
  30. 'This is a template.',
  31. ],
  32. [
  33. 'cache',
  34. Argument::OPTIONAL,
  35. 'This is a cache path.',
  36. 'cache',
  37. ],
  38. ];
  39. }
  40. }

tests/Console/Command/template

  1. hello make file
  2. {{key1}}
  3. {{key2}}
  4. {{key3}}
  5. {{key4}}
  1. public function testBaseUse(): void
  2. {
  3. $result = $this->runCommand(new MakeFile(), [
  4. 'command' => 'make:test',
  5. 'name' => 'test',
  6. ]);
  7. $result = $this->normalizeContent($result);
  8. $this->assertStringContainsString($this->normalizeContent('test <test> created successfully.'), $result);
  9. $file = __DIR__.'/Command/cache/test';
  10. $this->assertStringContainsString('hello make file', $content = file_get_contents($file));
  11. $this->assertStringContainsString('hello key1', $content);
  12. $this->assertStringContainsString('hello key2', $content);
  13. $this->assertStringContainsString('hello key3', $content);
  14. $this->assertStringContainsString('hello key4', $content);
  15. unlink($file);
  16. rmdir(dirname($file));
  17. }