Skip to content

Commit d506b43

Browse files
committed
fix add crudtrait to crud
1 parent c5543d2 commit d506b43

File tree

1 file changed

+14
-27
lines changed

1 file changed

+14
-27
lines changed

src/Console/Commands/CrudModelBackpackCommand.php

Lines changed: 14 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Backpack\Generators\Console\Commands;
44

55
use Backpack\Generators\Services\BackpackCommand;
6+
use Illuminate\Support\Facades\File;
67
use Illuminate\Support\Str;
78

89
class CrudModelBackpackCommand extends BackpackCommand
@@ -101,45 +102,31 @@ public function handle()
101102
if (! $this->hasOption('force') || ! $this->option('force')) {
102103
$this->progressBlock('Adding CrudTrait to the Model');
103104

104-
$file = $this->files->get($path);
105-
$lines = preg_split('/(\r\n)|\r|\n/', $file);
105+
$content = Str::of($this->files->get($path));
106106

107107
// check if it already uses CrudTrait
108108
// if it does, do nothing
109-
if (Str::contains($file, $this->crudTrait)) {
109+
if (Str::contains($content, $this->crudTrait)) {
110110
$this->closeProgressBlock('Already existed', 'yellow');
111111

112112
return false;
113-
}
114-
115-
// if it does not have CrudTrait, add the trait on the Model
116-
foreach ($lines as $key => $line) {
117-
if (Str::contains($line, "class {$name} extends")) {
118-
if (Str::endsWith($line, '{')) {
119-
// add the trait on the next
120-
$position = $key + 1;
121-
} elseif ($lines[$key + 1] == '{') {
122-
// add the trait on the next next line
123-
$position = $key + 2;
124-
}
113+
} else {
114+
$modifiedContent = Str::of(Str::before($content, ';'))
115+
->append(';'.PHP_EOL.PHP_EOL.'use Backpack\CRUD\app\Models\Traits\CrudTrait;');
125116

126-
// keep in mind that the line number shown in IDEs is not
127-
// the same as the array index - arrays start counting from 0,
128-
// IDEs start counting from 1
117+
$content = $content->after(';');
129118

130-
// add CrudTrait
131-
array_splice($lines, $position, 0, " use \\{$this->crudTrait};");
119+
$hasNewLine = str_starts_with($content, '\n') ? 1 : 0;
132120

133-
// save the file
134-
$this->files->put($path, implode(PHP_EOL, $lines));
121+
$modifiedContent = $modifiedContent->append(substr($content, strpos($content, "\n") + $hasNewLine));
135122

136-
// let the user know what we've done
137-
$this->closeProgressBlock();
123+
// save the file
124+
$this->files->put($path, $modifiedContent);
125+
// let the user know what we've done
126+
$this->closeProgressBlock();
138127

139-
return false;
140-
}
128+
return true;
141129
}
142-
143130
// In case we couldn't add the CrudTrait
144131
$this->errorProgressBlock();
145132
$this->note("Model already existed on '$name' and we couldn't add CrudTrait. Please add it manually.", 'red');

0 commit comments

Comments
 (0)