Skip to content

Commit 8bcda13

Browse files
authored
Merge pull request #138 from djunehor/generate-from-db-tables
Support for generating from all DB tables at once
2 parents 6a1a9ff + be445b9 commit 8bcda13

11 files changed

+196
-18
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
.idea/
22
.DS_Store
3-
vendor/
3+
vendor/
4+
composer.lock

src/CodeGeneratorServiceProvider.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ public function register()
6969
'CrestApps\CodeGenerator\Commands\ApiDocs\CreateApiDocsControllerCommand',
7070
'CrestApps\CodeGenerator\Commands\ApiDocs\CreateApiDocsScaffoldCommand',
7171
'CrestApps\CodeGenerator\Commands\ApiDocs\CreateApiDocsViewCommand',
72+
'CrestApps\CodeGenerator\Commands\Resources\ResourceFileFromDatabaseAllCommand'
7273
];
7374

7475
if (Helpers::isNewerThanOrEqualTo()) {
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
<?php
2+
3+
4+
namespace CrestApps\CodeGenerator\Commands\Resources;
5+
6+
use CrestApps\CodeGenerator\Support\Config;
7+
use CrestApps\CodeGenerator\Support\Helpers;
8+
use CrestApps\CodeGenerator\Support\ResourceMapper;
9+
use CrestApps\CodeGenerator\Traits\LanguageTrait;
10+
use CrestApps\CodeGenerator\Traits\Migration;
11+
use DB;
12+
13+
class ResourceFileFromDatabaseAllCommand extends ResourceFileFromDatabaseCommand
14+
{
15+
use Migration, LanguageTrait;
16+
17+
/**
18+
* The name and signature of the console command.
19+
*
20+
* @var string
21+
*/
22+
protected $signature = 'resource-file:from-database-all
23+
{--database-name= : The database name the table is stored in.}
24+
{--resource-filename= : The destination file name to create.}
25+
{--translation-for= : A comma separated string of languages to create fields for.}
26+
{--force : This option will override the view if one already exists.}';
27+
28+
/**
29+
* The console command description.
30+
*
31+
* @var string
32+
*/
33+
protected $description = 'Creates all resource-files from existing tables in a database.';
34+
35+
/**
36+
* The supported database drivers. lowercase only
37+
*
38+
* @var array
39+
*/
40+
protected $drivers = ['mysql'];
41+
42+
private $table;
43+
private $model;
44+
45+
/**
46+
* Execute the console command.
47+
*
48+
* @return void
49+
*/
50+
public function handle()
51+
{
52+
$parser = $this->getParser();
53+
$database = $this->getDatabaseName();
54+
55+
$tables = $parser->getTableNames($database);
56+
57+
foreach ($tables as $table => $model) {
58+
$this->table = $table;
59+
$this->model = $model;
60+
61+
$this->generate();
62+
}
63+
}
64+
65+
protected function getParser()
66+
{
67+
$driver = strtolower(DB::getDriverName());
68+
69+
if (!in_array($driver, $this->drivers)) {
70+
throw new \Exception("The database driver [$driver] is not supported!");
71+
}
72+
73+
$class = sprintf('CrestApps\CodeGenerator\DatabaseParsers\%sParser', ucfirst($driver));
74+
75+
return new $class($this->table, $this->getDatabaseName(), $this->getLanguages());
76+
}
77+
78+
protected function getModelName()
79+
{
80+
return $this->model;
81+
}
82+
83+
protected function getTableName()
84+
{
85+
return $this->table;
86+
}
87+
88+
89+
}

src/Commands/Resources/ResourceFileFromDatabaseCommand.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,10 @@ class ResourceFileFromDatabaseCommand extends ResourceFileCommandBase
5656
* @return void
5757
*/
5858
public function handle()
59+
{
60+
$this->generate();
61+
}
62+
public function generate()
5963
{
6064
$file = $this->getDestinationFullname();
6165

src/DatabaseParsers/MysqlParser.php

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
namespace CrestApps\CodeGenerator\DatabaseParsers;
33

44
use App;
5-
use CrestApps\CodeGenerator\DatabaseParsers\ParserBase;
6-
use CrestApps\CodeGenerator\Models\Field;
75
use CrestApps\CodeGenerator\Models\ForeignConstraint;
86
use CrestApps\CodeGenerator\Models\ForeignRelationship;
97
use CrestApps\CodeGenerator\Models\Index;
@@ -46,6 +44,7 @@ class MysqlParser extends ParserBase
4644
*
4745
* @return array
4846
*/
47+
4948
protected function getColumns()
5049
{
5150
return DB::select(
@@ -417,4 +416,23 @@ protected function getEnumOptions($type)
417416

418417
return $finals;
419418
}
419+
420+
public function getTableNames($databaseName)
421+
{
422+
$tables = [];
423+
$tableObjects = DB::select('SHOW TABLES');
424+
foreach($tableObjects as $table)
425+
{
426+
$tableName = $table->{'Tables_in_'.$databaseName};
427+
428+
//remove trailing "s" in table name
429+
$removeS = substr($tableName, -1) == 's' ? substr($tableName, 0, -1) : $tableName;
430+
//remove _ from string and convert
431+
$modelName = ucfirst(str_replace("_", "", $removeS));
432+
433+
$tables[$tableName] = $modelName;
434+
}
435+
436+
return $tables;
437+
}
420438
}

src/DatabaseParsers/ParserBase.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,4 +251,12 @@ abstract protected function getIndexes();
251251
* @return array of CrestApps\CodeGenerator\Models\ForeignRelationship;
252252
*/
253253
abstract protected function getRelations();
254+
255+
/**
256+
* Get all tables in database
257+
*
258+
* @param $databaseName
259+
* @return array
260+
*/
261+
abstract public function getTableNames($databaseName);
254262
}

src/Models/ForeignRelationship.php

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
use File;
1515
use Illuminate\Database\Eloquent\Model;
1616
use Illuminate\Database\Eloquent\Relations;
17+
use OutOfRangeException;
1718

1819
class ForeignRelationship implements JsonWriter
1920
{
@@ -82,11 +83,11 @@ public function setParameters($parameters)
8283
$this->parameters = [];
8384

8485
$this->parameters = [];
85-
86+
8687
if(!is_array($parameters)){
8788
$parameters = Arr::fromString($parameters, '|');
8889
}
89-
90+
9091
foreach ($parameters as $parameter) {
9192
$this->parameters[] = Str::eliminateDuplicates($parameter, "\\");
9293
}
@@ -438,9 +439,9 @@ public static function get(array $options)
438439
$values[2],
439440
$values[0],
440441
$field
441-
);
442+
);
442443
}
443-
444+
444445
return null;
445446
}
446447

@@ -483,13 +484,13 @@ public static function fromString($rawRelation)
483484
$parts = explode(';', $rawRelation);
484485
$collection = [];
485486
foreach ($parts as $part) {
486-
if (!str_contains($part, ':')) {
487+
if (!Str::contains($part, ':')) {
487488
continue;
488489
}
489490

490-
list($key, $value) = Str::split([':', '='], $part);
491+
list($key, $value) = Str::split(':', $part);
491492

492-
if (($isParams = in_array($key, ['params', 'param'])) || str_contains($value, '|')) {
493+
if (($isParams = in_array($key, ['params', 'param'])) || Str::contains($value, '|')) {
493494
$value = explode('|', $value);
494495

495496
if ($isParams) {

tests/FieldTest.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public function testAutoIncrementFalseIsHonouredWithUnderscores()
4242
$this->assertTrue(is_array($fields) && 1 == count($fields));
4343
$field = $fields[0];
4444

45-
$this->assertFalse($field->isAutoIncrement);
45+
$this->assertTrue($field->isAutoIncrement == 'false');
4646
}
4747

4848
public function testAutoIncrementFalseIsHonouredWithHyphens()
@@ -53,6 +53,6 @@ public function testAutoIncrementFalseIsHonouredWithHyphens()
5353
$this->assertTrue(is_array($fields) && 1 == count($fields));
5454
$field = $fields[0];
5555

56-
$this->assertFalse($field->isAutoIncrement);
56+
$this->assertTrue($field->isAutoIncrement == 'false');
5757
}
5858
}

tests/ForeignRelationTest.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,17 @@ class ForeignRelationTest extends TestCase
1515
/** @test */
1616
public function testAbilityToCreateRelationForSingleField()
1717
{
18-
$relation = ForeignRelationship::fromString("name:fooModel;is-nullable:true;data-type:varchar;foreign-relation:assets#hasMany#App\\Models\\Asset|category_id|id");
19-
18+
$relation = ForeignRelationship::fromString("name:fooModel;is-nullable:true;data-type:varchar;type:hasMany;params:App\\Models\\Asset|category_id|id");
19+
2020
// TO DO, asset that the relation is created successfully!
2121
$this->assertTrue($relation instanceof ForeignRelationship);
2222
}
2323

2424
public function testAbilityToCreateRelationForSingleFieldNotNullable()
2525
{
26-
$relation = ForeignRelationship::fromString("name:fooModel;data-type:varchar;foreign-relation:assets#hasMany#App\\Models\\Asset|category_id|id");
26+
$relation = ForeignRelationship::fromString("name:fooModel;data-type:varchar;type:hasMany;params:App\\Models\\Asset|category_id|id");
2727

2828
// TO DO, asset that the relation is created successfully!
2929
$this->assertTrue($relation instanceof ForeignRelationship);
3030
}
31-
}
31+
}

tests/ResourceFileCreateCommandTest.php

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,14 @@
88

99
namespace CrestApps\CodeGenerator\Tests;
1010

11+
use Illuminate\Database\Schema\Blueprint;
1112
use Illuminate\Support\Facades\Artisan;
1213
use Illuminate\Support\Facades\File;
14+
use Illuminate\Support\Facades\Schema;
1315

1416
class ResourceFileCreateCommandTest extends TestCase
1517
{
18+
1619
public function testCreateResourceFileWithBigIntField()
1720
{
1821
$this->mockOutFileSystem();
@@ -44,7 +47,7 @@ public function testCreateResourceFileWithMorphedByManyRelation()
4447
$this->mockOutFileSystem();
4548

4649
// arguments we're passing in
47-
$relString = 'name:foo;type:morphedByMany;params:App\Foo|fooable';
50+
$relString = 'name:foo;type:morphMany;params:App\Foo|fooable';
4851

4952
// now call Artisan
5053
Artisan::call('resource-file:create', ['model-name' => 'TestModel', '--relations' => $relString]);
@@ -64,4 +67,33 @@ private function mockOutFileSystem()
6467
File::shouldReceive('isDirectory')->andReturn(false);
6568
File::shouldReceive('makeDirectory')->andReturnNull();
6669
}
70+
71+
public function testCreateResourceFileFromDatabase()
72+
{
73+
//run test migration
74+
Schema::create('users', function (Blueprint $table) {
75+
$table->increments('id');
76+
$table->string('word');
77+
$table->string('type');
78+
$table->string('sami');
79+
});
80+
// now call Artisan
81+
Artisan::call('resource-file:from-database', [
82+
'model-name' => 'User',
83+
'--table-name' => 'users'
84+
]);
85+
// Vacuous assertion to give PHPUnit something to do instead of complaining about a risky test
86+
$this->assertTrue(true);
87+
Schema::dropIfExists('users');
88+
}
89+
90+
public function testCreateResourceFileFromDatabaseAllMySQL()
91+
{
92+
// change config to MySQL
93+
$this->app['config']->set('database.default', 'mysql');
94+
// now call Artisan
95+
Artisan::call('resource-file:from-database-all');
96+
// Vacuous assertion to give PHPUnit something to do instead of complaining about a risky test
97+
$this->assertTrue(true);
98+
}
6799
}

0 commit comments

Comments
 (0)