diff --git a/src/Generators/AbstractGenerator.php b/src/Generators/AbstractGenerator.php index ee6d0b4..98d32e7 100644 --- a/src/Generators/AbstractGenerator.php +++ b/src/Generators/AbstractGenerator.php @@ -7,6 +7,8 @@ abstract class AbstractGenerator { + public bool $overwriteExistingFile = true; + public function __construct(protected string $name, protected ?string $module = null) { $this->name = Str::singular($this->name); @@ -116,7 +118,14 @@ public function write(): void mkdir($dir, 0777, true); } - file_put_contents($file, $this->content()); + if ($this->shouldWriteFile($file)) { + file_put_contents($file, $this->content()); + } + } + + public function shouldWriteFile(string $file): bool + { + return $this->overwriteExistingFile || ! file_exists($file); } public function content(): string diff --git a/src/Generators/ModuleServiceProviderGenerator.php b/src/Generators/ModuleServiceProviderGenerator.php index 6b96828..605293f 100644 --- a/src/Generators/ModuleServiceProviderGenerator.php +++ b/src/Generators/ModuleServiceProviderGenerator.php @@ -6,6 +6,8 @@ class ModuleServiceProviderGenerator extends AbstractGenerator { + public bool $overwriteExistingFile = false; + public function className(): string { return sprintf('%sServiceProvider', Str::singular($this->module())); diff --git a/tests/Generators/GeneratorTestAbstract.php b/tests/Generators/GeneratorTestAbstract.php index bda9f42..f44795e 100644 --- a/tests/Generators/GeneratorTestAbstract.php +++ b/tests/Generators/GeneratorTestAbstract.php @@ -14,7 +14,7 @@ public function testGenerator(string $name, string $module, string $expectedPath foreach ($config as $key => $value) { config()->set($key, $value); } - + $generator = $this->generator($name, $module); $generator->write(); @@ -28,7 +28,7 @@ public function testGenerator(string $name, string $module, string $expectedPath } } - private function generator(string $name, string $module): AbstractGenerator + public function generator(string $name, string $module): AbstractGenerator { $generatorClassName = $this->generatorClassName(); return new $generatorClassName($name, $module ?: null); diff --git a/tests/Generators/ModuleServiceProviderGeneratorTest.php b/tests/Generators/ModuleServiceProviderGeneratorTest.php index b054ff5..85ae7c3 100644 --- a/tests/Generators/ModuleServiceProviderGeneratorTest.php +++ b/tests/Generators/ModuleServiceProviderGeneratorTest.php @@ -24,4 +24,19 @@ public static function dataGenerator(): array ], ]; } + + public function testItDoesNotOverwriteAnExistingFile(): void + { + $expectedFile = base_path('app-modules/Posts/src/PostServiceProvider.php'); + + // a Module can contain multiple CRUDs + // we always only want to create a ModuleServiceProvider once + $generator = $this->generator('Post', 'Posts'); + + $this->assertTrue($generator->shouldWriteFile($expectedFile)); + + $generator->write(); + + $this->assertFalse($generator->shouldWriteFile($expectedFile)); + } }