From bcec1e330c770ad8996ccbd11b4fb0f5398fd3b6 Mon Sep 17 00:00:00 2001 From: Nafies Luthfi Date: Sun, 14 Mar 2021 23:58:58 +0800 Subject: [PATCH] Prevent overriding the existing model policy class --- src/Generators/ModelPolicyGenerator.php | 10 +++++--- tests/Generators/ModelPolicyGeneratorTest.php | 36 +++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/src/Generators/ModelPolicyGenerator.php b/src/Generators/ModelPolicyGenerator.php index 8f6dbd6..5df21e0 100644 --- a/src/Generators/ModelPolicyGenerator.php +++ b/src/Generators/ModelPolicyGenerator.php @@ -17,11 +17,13 @@ class ModelPolicyGenerator extends BaseGenerator $parentDirectory = '/'.$this->command->option('parent'); } $modelPolicyPath = $this->makeDirectory(app_path('Policies'.$parentDirectory)); + $modelPolicyClassPath = $modelPolicyPath.'/'.$this->modelNames['model_name'].'Policy.php'; - $this->generateFile( - $modelPolicyPath.'/'.$this->modelNames['model_name'].'Policy.php', - $this->getContent('models/model-policy') - ); + if ($this->files->exists($modelPolicyClassPath)) { + return; + } + + $this->generateFile($modelPolicyClassPath, $this->getContent('models/model-policy')); $this->command->info($this->modelNames['model_name'].' model policy generated.'); diff --git a/tests/Generators/ModelPolicyGeneratorTest.php b/tests/Generators/ModelPolicyGeneratorTest.php index 63fd0ba..7cfc45f 100644 --- a/tests/Generators/ModelPolicyGeneratorTest.php +++ b/tests/Generators/ModelPolicyGeneratorTest.php @@ -229,4 +229,40 @@ class AuthServiceProvider extends ServiceProvider "; $this->assertEquals($authSPContent, file_get_contents($authSPPath)); } + + /** @test */ + public function it_doesnt_override_the_existing_model_policy_content() + { + $userModel = config('auth.providers.users.model'); + + $this->artisan('make:policy', ['name' => $this->model_name.'Policy', '--no-interaction' => true]); + $this->artisan('make:crud', ['name' => $this->model_name, '--no-interaction' => true]); + + $modelPolicyPath = app_path('Policies/'.$this->model_name.'Policy.php'); + // dd(file_get_contents($modelPolicyPath)); + $this->assertFileExists($modelPolicyPath); + $modelPolicyContent = "model_name}Policy +{ + use HandlesAuthorization; + + /** + * Create a new policy instance. + * + * @return void + */ + public function __construct() + { + // + } +} +"; + $this->assertEquals($modelPolicyContent, file_get_contents($modelPolicyPath)); + } }