Skip to content

Instantly share code, notes, and snippets.

@AnandPilania
Created February 13, 2021 16:08
Show Gist options
  • Save AnandPilania/da4ddbc407b97c9ce89ff130a5dc9c1e to your computer and use it in GitHub Desktop.
Save AnandPilania/da4ddbc407b97c9ce89ff130a5dc9c1e to your computer and use it in GitHub Desktop.
Extends Laravel's default `model:make` command, than support Nova Resource (if using Laravel Nova); create Policy & add mapping to `AuthServiceProvider`
<?php
namespace App\Traits;
use Illuminate\Support\Str;
trait InsertLineTrait
{
public function insertLineAfter($path, $needle, $replace)
{
return $this->insertLine($path, $needle, $replace, true);
}
public function insertLineBefore($path, $needle, $replace)
{
return $this->insertLine($path, $needle, $replace, false);
}
public function insertLine($path, $needle, $insert, $after = true)
{
if (!file_exists($path)) {
return "The file doesn't exists!";
}
$content = file_get_contents($path);
if (Str::contains($content, $insert)) {
return "The line already exists";
}
$contentToReplace = collect(explode("\n", $content))->map(
function ($line) use ($needle, $insert, $after) {
if (Str::contains($line, $needle)) {
return $after ? "$line\n$insert" : "$insert\n$line";
}
return $line;
}
)->join("\n");
if ($contentToReplace != $content) {
file_put_contents($path, $contentToReplace);
return "Line Added '$insert'";
} else {
return "Unmodified Content. '$insert' line not added";
}
}
}
<?php
namespace App\Console\Commands;
use App\Traits\InsertLineTrait;
use Illuminate\Foundation\Console\ModelMakeCommand as Command;
use Symfony\Component\Console\Input\InputOption;
class ModelMakeCommand extends Command
{
use InsertLineTrait;
public function handle()
{
parent::handle();
$modelName = $this->argument('name');
if (class_exists(\Laravel\Nova\NovaServiceProvider::class) && $this->option('nova-resource')) {
$this->call('nova:resource', [
'name' => $modelName,
'--model' => $modelName
]);
}
if ($this->option('policy') || $policyName = $this->option('policy-name')) {
$policyName = isset($policyName) ? $policyName : $modelName . 'Policy';
$this->call('make:policy', [
'name' => $policyName,
'--model' => $modelName
]);
$this->insertLineAfter(
app_path('Providers/AuthServiceProvider.php'),
"protected \$policies = [",
"\t\t" . trim("'App\Models\\" . $modelName . "' => 'App\Policies\\" . $policyName . "',")
);
}
}
protected function getOptions()
{
$policyOptions = array_merge([
['policy', 'P', InputOption::VALUE_NONE, 'Create Model with Policy.'],
['policy-name', 'PN', InputOption::VALUE_OPTIONAL, 'Policy name.'],
], parent::getOptions());
return class_exists(\Laravel\Nova\NovaServiceProvider::class)
? array_merge([
['nova-resource', 'N', InputOption::VALUE_NONE, 'Create Nova Resource for this model class.'],
], $policyOptions)
: $policyOptions;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment