Skip to content

Instantly share code, notes, and snippets.

@AnandPilania
Created February 13, 2021 16:03
Show Gist options
  • Save AnandPilania/ea36b86b2f0ea238ff2a38b7fa4e115e to your computer and use it in GitHub Desktop.
Save AnandPilania/ea36b86b2f0ea238ff2a38b7fa4e115e to your computer and use it in GitHub Desktop.
Generate Policies & Models (if not created yet) from AuthServiceProvider's mapped Policies.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider;
use Illuminate\Support\Str;
class PolicyGenerateCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'policy:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate Policies & Models from AuthServiceProvider\'s mapped Policies.';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$providers = $this->laravel->getProviders(AuthServiceProvider::class);
foreach ($providers as $provider) {
foreach ($provider->policies() as $model => $policy) {
$this->makeModelAndPolicy($model, $policy);
}
}
}
protected function makeModelAndPolicy($model, $policy)
{
if (!Str::contains($model, '\\')) {
return;
}
$this->call('make:model', ['name' => $model]);
$this->makePolicy($model, $policy);
}
protected function makePolicy($model, $policy)
{
$policy = preg_replace('/@.+$/', '', $policy);
$this->call('make:policy', array_filter(
['name' => $policy, '--model' => $model]
));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment