1: <?php
2:
3: namespace Baril\Bonsai\Console;
4:
5: use Baril\Bonsai\Console\Concerns\InteractsWithTree;
6: use Illuminate\Database\Console\Migrations\MigrateMakeCommand;
7: use Illuminate\Support\Str;
8:
9: /**
10: * @todo remove --migrate option in v4
11: */
12: class GrowTreeCommand extends MigrateMakeCommand
13: {
14: use InteractsWithTree;
15:
16: protected $signature = 'bonsai:grow {model : The model class}
17: {--name= : The name of the migration}
18: {--path= : The location where the migration file should be created}
19: {--realpath : Indicate any provided migration file paths are pre-resolved absolute paths}
20: {--migrate : Migrate the database and fill the table after the migration file has been created. (Deprecated)}';
21: protected $description = 'Create the migration file for a closure table, and optionally run the migration';
22:
23: public function handle()
24: {
25: $model = $this->input->getArgument('model');
26:
27: $this->checkModel($model);
28:
29: $this->writeClosureMigration($model);
30: $this->composer->dumpAutoloads();
31:
32: if ($this->input->hasOption('migrate') && $this->option('migrate')) {
33: $this->call('migrate');
34: $this->call('bonsai:fix', ['model' => $model]);
35: }
36: }
37:
38: protected function writeClosureMigration($model)
39: {
40: // Retrieve all informations about the tree:
41: $instance = new $model();
42: $closureTable = $instance->getClosureTable();
43:
44: // Get the name for the migration file:
45: $name = $this->input->getOption('name') ?: 'create_' . $closureTable . '_table';
46: $name = Str::snake(trim($name));
47: $migrationClassName = Str::studly($name);
48:
49: // Generate the content of the migration file:
50: $contents = $this->getMigrationContents([
51: '%migration%' => $migrationClassName,
52: '%closureTable%' => $closureTable,
53: '%mainTable%' => $instance->getTable(),
54: '%model%' => get_class($instance),
55: ]);
56:
57: // Generate the file:
58: $file = $this->creator->create(
59: $name,
60: $this->getMigrationPath(),
61: $closureTable,
62: true
63: );
64: file_put_contents($file, $contents);
65:
66: // Output information:
67: $file = pathinfo($file, PATHINFO_FILENAME);
68: $this->line("<info>Created Migration:</info> {$file}");
69: }
70:
71: protected function getMigrationContents($replacements)
72: {
73: $contents = file_get_contents(__DIR__ . '/../Migrations/stubs/grow_tree.stub');
74: $contents = str_replace(
75: array_keys($replacements),
76: array_values($replacements),
77: $contents
78: );
79: $contents = preg_replace('/\;[\s]*\/\/.*\n/U', ";\n", $contents);
80: return $contents;
81: }
82: }
83: