Skip to content

Commit eb89cb4

Browse files
committed
Fixed couple of bugs related to creating resources that does not follow the standard naming convention
1 parent 332f2d1 commit eb89cb4

16 files changed

+259
-87
lines changed

config/codegenerator.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -599,7 +599,10 @@
599599
'datetimetz' => 'dateTimeTz',
600600
'biginteger' => 'bigIncrements',
601601
'bigint' => 'bigIncrements',
602+
'tinyblob' => 'binary',
603+
'mediumblob' => 'binary',
602604
'blob' => 'binary',
605+
'longblob' => 'binary',
603606
'binary' => 'binary',
604607
'bool' => 'boolean',
605608
'boolean' => 'boolean',

src/Commands/CreateControllerCommand.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -468,7 +468,7 @@ protected function getControllerExtends($namespace)
468468
*/
469469
protected function getControllersNamespace($path)
470470
{
471-
$path = $this->getAppNamespace() . Config::getControllersPath($path);
471+
$path = Helpers::getAppNamespace() . Config::getControllersPath($path);
472472

473473
return rtrim(Helpers::convertSlashToBackslash($path), '\\');
474474
}
@@ -502,7 +502,7 @@ protected function getFullClassToExtend($extend)
502502
if (empty($extend)) {
503503
return '';
504504
}
505-
$appNamespace = $this->getAppNamespace();
505+
$appNamespace = Helpers::getAppNamespace();
506506

507507
if (starts_with($extend, $appNamespace)) {
508508
$extend = str_replace($appNamespace, '', $extend);
@@ -525,7 +525,7 @@ protected function getModelNamespace($modelName, $modelDirectory)
525525
$modelDirectory = str_finish($modelDirectory, '\\');
526526
}
527527

528-
$namespace = $this->getAppNamespace() . Config::getModelsPath($modelDirectory . $modelName);
528+
$namespace = Helpers::getAppNamespace() . Config::getModelsPath($modelDirectory . $modelName);
529529

530530
return rtrim(Helpers::convertSlashToBackslash($namespace), '\\');
531531
}
@@ -626,7 +626,7 @@ protected function getRequestsNamespace($name, $path)
626626
$path = str_finish($path, '\\');
627627
}
628628

629-
$path = $this->getAppNamespace() . Config::getRequestsPath($path);
629+
$path = Helpers::getAppNamespace() . Config::getRequestsPath($path);
630630

631631
return Helpers::convertSlashToBackslash($path) . $name;
632632
}

src/Commands/CreateFormRequestCommand.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ protected function getRequestsNamespace($path)
170170
{
171171
$path = str_finish($path, '\\');
172172

173-
$path = $this->getAppNamespace() . Config::getRequestsPath($path);
173+
$path = Helpers::getAppNamespace() . Config::getRequestsPath($path);
174174

175175
return rtrim(Helpers::convertSlashToBackslash($path), '\\');
176176
}

src/Commands/CreateModelCommand.php

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,6 @@ public function handle()
7070
$fields = $this->upsertDeletedAt($fields);
7171
}
7272

73-
$primaryKey = $this->getNewPrimaryKey($this->getPrimaryKeyName($fields, $input->primaryKey));
7473
$destenationFile = $this->getDestenationFile($input->modelName, $input->modelDirectory);
7574

7675
if ($this->alreadyExists($destenationFile)) {
@@ -80,16 +79,16 @@ public function handle()
8079
}
8180

8281
$relations = $this->getRelationMethods($resources->relations, $fields);
83-
82+
$primaryField = $this->getPrimaryField($fields);
8483
return $this->replaceTable($stub, $input->table)
8584
->replaceModelName($stub, $input->modelName)
8685
->replaceNamespace($stub, $this->getNamespace($input->modelName, $input->modelDirectory))
8786
->replaceSoftDelete($stub, $input->useSoftDelete)
88-
->replaceTimestamps($stub, $this->getTimeStampsStub($input->useTimeStamps))
87+
->replaceTimestamps($stub, $this->getTimeStampsStub($input->useTimeStamps, $resources->isCreateAndUpdateAtManaged()))
8988
->replaceFillable($stub, $this->getFillables($stub, $fields))
9089
->replaceDateFields($stub, $this->getDateFields($stub, $fields))
9190
->replaceCasts($stub, $this->getCasts($stub, $fields))
92-
->replacePrimaryKey($stub, $primaryKey)
91+
->replacePrimaryKey($stub, $this->getNewPrimaryKey($primaryField, $input->primaryKey))
9392
->replaceRelationshipPlaceholder($stub, $relations)
9493
->replaceAccessors($stub, $this->getAccessors($fields))
9594
->replaceMutators($stub, $this->getMutators($fields))
@@ -124,23 +123,21 @@ protected function getDestenationFile($name, $path)
124123
*/
125124
protected function getNamespace($modelName, $modelDirectory)
126125
{
127-
$namespace = $this->getAppNamespace() . Config::getModelsPath($modelDirectory);
126+
$namespace = Helpers::getAppNamespace() . Config::getModelsPath($modelDirectory);
128127

129128
return rtrim(Helpers::convertSlashToBackslash($namespace), '\\');
130129
}
131130

132131
/**
133132
* Gets the correct primary key name.
134133
*
135-
* @param array $fields
134+
* @param CreatApps\CodeGenerator\Models\Field $primaryField
136135
* @param string $primaryKey
137136
*
138137
* @return string
139138
*/
140-
protected function getPrimaryKeyName(array $fields, $primaryKey)
139+
protected function getPrimaryKeyName(Field $primaryField, $primaryKey)
141140
{
142-
$primaryField = $this->getPrimaryField($fields);
143-
144141
return !is_null($primaryField) ? $primaryField->name : $primaryKey;
145142
}
146143

@@ -154,12 +151,13 @@ protected function getPrimaryKeyName(array $fields, $primaryKey)
154151
protected function upsertDeletedAt(array $fields)
155152
{
156153
foreach ($fields as $field) {
157-
if ($field->name == 'deleted_at') {
154+
if ($field->isAutoManagedOnDelete()) {
158155
return $fields;
159156
}
160157
}
161158

162159
$fields[] = $this->getNewDeletedAtField();
160+
163161
return $fields;
164162
}
165163

@@ -480,11 +478,19 @@ protected function getRelationshipMethod(ForeignRelationship $relation)
480478
* @param string $rootNamespace
481479
* @return string
482480
*/
483-
protected function getNewPrimaryKey($primaryKey)
481+
protected function getNewPrimaryKey(Field $primaryKey = null, $defaultName = 'id')
484482
{
485483
$stub = $this->getStubContent('model-primary-key');
486484

487-
$this->replacePrimaryKey($stub, $primaryKey);
485+
$this->replacePrimaryKey($stub, $this->getPrimaryKeyName($primaryKey, $defaultName));
486+
487+
if (!is_null($primaryKey) && !$primaryKey->isNumeric()) {
488+
$lines = explode("\n", $stub);
489+
$last = end($lines);
490+
$spaces = str_repeat(' ', $this->getIndent($last, 'p'));
491+
$stub .= PHP_EOL . $spaces . 'protected $keyType = \'string\';' . PHP_EOL;
492+
$stub .= $spaces . 'public $incrementing = false;' . PHP_EOL;
493+
}
488494

489495
return $stub;
490496
}
@@ -493,15 +499,17 @@ protected function getNewPrimaryKey($primaryKey)
493499
* Gets the timestamp block.
494500
*
495501
* @param bool $shouldUseTimeStamps
502+
* @param bool $hasUpdatedAt
496503
*
497504
* @return string
498505
*/
499-
protected function getTimeStampsStub($shouldUseTimeStamps)
506+
protected function getTimeStampsStub($shouldUseTimeStamps, $hasUpdatedAt)
500507
{
501-
if ($shouldUseTimeStamps) {
502-
return null;
508+
if (!$shouldUseTimeStamps || !$hasUpdatedAt) {
509+
return $this->getStubContent('model-timestamps');
503510
}
504-
return $this->getStubContent('model-timestamps');
511+
512+
return null;
505513
}
506514

507515
/**

src/Commands/CreateResourcesCommand.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,7 @@ protected function createMigration($input)
167167
*/
168168
protected function createResourceFile($input)
169169
{
170+
170171
$this->call(
171172
'resource-file:from-database',
172173
[

src/DatabaseParsers/MysqlParser.php

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,11 @@ class MysqlParser extends ParserBase
3939
protected $largeDataTypes = ['varbinary', 'blob', 'mediumblob', 'longblob', 'text', 'mediumtext', 'longtext'];
4040

4141
/**
42-
* Gets column meta info from the information schema.
42+
* Gets columns meta info from the information schema.
4343
*
4444
* @return array
4545
*/
46-
protected function getColumn()
46+
protected function getColumns()
4747
{
4848
return DB::select(
4949
'SELECT
@@ -94,6 +94,7 @@ protected function getConstraints()
9494
,r.DELETE_RULE AS `onDelete`
9595
,u.referenced_column_name AS `on`
9696
,u.column_name AS `foreign`
97+
,CASE WHEN u.TABLE_NAME = r.referenced_table_name THEN 1 ELSE 0 END selfReferences
9798
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS r
9899
INNER JOIN information_schema.key_column_usage AS u ON u.CONSTRAINT_NAME = r.CONSTRAINT_NAME
99100
AND u.table_schema = r.constraint_schema
@@ -132,9 +133,8 @@ protected function getRelations()
132133
{
133134
$relations = [];
134135
$rawRelations = $this->getRawRelations();
135-
136136
foreach ($rawRelations as $rawRelation) {
137-
$relations[] = $this->getRealtion($rawRelation->foreignTable, $rawRelation->foreignKey, $rawRelation->localKey);
137+
$relations[] = $this->getRealtion($rawRelation->foreignTable, $rawRelation->foreignKey, $rawRelation->localKey, $rawRelation->selfReferences);
138138
}
139139

140140
return $relations;
@@ -153,6 +153,7 @@ protected function getRawRelations()
153153
u.referenced_column_name AS `localKey`
154154
,u.column_name AS `foreignKey`
155155
,r.table_name AS `foreignTable`
156+
,CASE WHEN u.TABLE_NAME = r.referenced_table_name THEN 1 ELSE 0 END selfReferences
156157
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS r
157158
INNER JOIN information_schema.key_column_usage AS u ON u.CONSTRAINT_NAME = r.CONSTRAINT_NAME
158159
AND u.table_schema = r.constraint_schema
@@ -184,22 +185,24 @@ protected function getRelationTypeQuery($tableName, $columnName)
184185
*
185186
* @return CrestApps\CodeGenerator\Models\ForeignRelationship
186187
*/
187-
protected function getRealtion($foreignTableName, $foreignColumn, $localColumn)
188+
protected function getRealtion($foreignTableName, $foreignColumn, $localColumn, $selfReferences)
188189
{
189190
$modelName = $this->getModelName($foreignTableName);
190-
$model = Helpers::guessModelFullName($modelName, $this->getModelNamespace());
191+
$model = Helpers::guessModelFullName($modelName, Helpers::getModelsPath());
191192

192193
$params = [
193194
$model,
194195
$foreignColumn,
195196
$localColumn,
196197
];
197198

199+
$relationName = ($selfReferences ? 'child_' : '');
200+
198201
if ($this->isOneToMany($foreignTableName, $foreignColumn)) {
199-
return new ForeignRelationship('hasMany', $params, camel_case(Str::plural($foreignTableName)));
202+
return new ForeignRelationship('hasMany', $params, camel_case($relationName . Str::plural($foreignTableName)));
200203
}
201204

202-
return new ForeignRelationship('hasOne', $params, camel_case(Str::singular($foreignTableName)));
205+
return new ForeignRelationship('hasOne', $params, camel_case($relationName . Str::singular($foreignTableName)));
203206
}
204207

205208
/**
@@ -255,7 +258,7 @@ protected function getTransfredFields(array $columns)
255258
$properties['data-value'] = $column->COLUMN_DEFAULT;
256259
$properties['data-type'] = $this->getDataType($column->DATA_TYPE, $column->COLUMN_TYPE);
257260
$properties['data-type-params'] = $this->getPrecision($column->CHARACTER_MAXIMUM_LENGTH, $column->DATA_TYPE, $column->COLUMN_TYPE);
258-
$properties['is-primary'] = ($column->COLUMN_KEY == 'PRIMARY KEY');
261+
$properties['is-primary'] = in_array($column->COLUMN_KEY, ['PRIMARY KEY', 'PRI']);
259262
$properties['is-index'] = ($column->COLUMN_KEY == 'MUL');
260263
$properties['is-unique'] = ($column->COLUMN_KEY == 'UNI');
261264
$properties['is-auto-increment'] = ($column->EXTRA == 'AUTO_INCREMENT');
@@ -274,7 +277,9 @@ protected function getTransfredFields(array $columns)
274277

275278
$collection[] = $properties;
276279
}
280+
277281
$localeGroup = Helpers::makeLocaleGroup($this->tableName);
282+
278283
$fields = FieldTransformer::fromArray($collection, $localeGroup, $this->languages);
279284

280285
// At this point we constructed the fields collection with the default html-type
@@ -353,11 +358,13 @@ protected function getForeignConstraint($name)
353358
}
354359

355360
return new ForeignConstraint(
356-
strtolower($raw->foreign),
357-
strtolower($raw->references),
358-
strtolower($raw->on),
361+
$raw->foreign,
362+
$raw->references,
363+
$raw->on,
359364
strtolower($raw->onDelete),
360-
strtolower($raw->onUpdate)
365+
strtolower($raw->onUpdate),
366+
null,
367+
$raw->selfReferences
361368
);
362369
}
363370

src/DatabaseParsers/ParserBase.php

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ public function __construct($tableName, $databaseName, array $languages = [])
8989
protected function getFields()
9090
{
9191
if (is_null($this->fields)) {
92-
$columns = $this->getColumn();
92+
$columns = $this->getColumns();
9393

9494
if (empty($columns)) {
9595
throw new Exception('The table ' . $this->tableName . ' was not found in the ' . $this->databaseName . ' database.');
@@ -108,13 +108,26 @@ protected function getFields()
108108
*/
109109
public function getResource()
110110
{
111-
$resource = new Resource($this->getFields());
112-
$resource->indexes = $this->getIndexes();
113-
$resource->relations = $this->getRelations();
111+
$fields = $this->getFields();
112+
$autoManage = $this->containsUpdateAtAndCreatedAt($fields);
113+
$resource = new Resource($fields, $this->getRelations(), $this->getIndexes(), $autoManage);
114114

115115
return $resource;
116116
}
117117

118+
/**
119+
* Check if the giving fields contains autoManagedFields
120+
*
121+
* @return CrestApps\CodeGenerator\Models\Resource
122+
*/
123+
protected function containsUpdateAtAndCreatedAt($fields)
124+
{
125+
$autoManagedFields = array_filter($fields, function ($field) {
126+
return $field->isAutoManagedOnUpdate();
127+
});
128+
129+
return count($autoManagedFields) == 2;
130+
}
118131
/**
119132
* Gets the final resource.
120133
*
@@ -130,17 +143,17 @@ public function getResourceAsJson()
130143
/**
131144
* Gets array of field after transfering each column meta into field.
132145
*
133-
* @param array $columns
146+
* @param array $fields
134147
*
135148
* @return array
136149
*/
137-
protected function transfer(array $columns)
150+
protected function transfer(array $fields)
138151
{
139-
$fields = array_map(function ($field) {
152+
$mappers = array_map(function ($field) {
140153
return new FieldMapper($field);
141-
}, $this->getTransfredFields($columns));
154+
}, $this->getTransfredFields($fields));
142155

143-
$optimizer = new FieldsOptimizer($fields);
156+
$optimizer = new FieldsOptimizer($mappers);
144157

145158
return $optimizer->optimize()->getFields();
146159
}
@@ -188,7 +201,7 @@ protected function setHtmlType(array &$fields)
188201
*/
189202
protected function getModelNamespace()
190203
{
191-
return $this->getAppNamespace() . Config::getModelsPath();
204+
return Helpers::getAppNamespace() . Config::getModelsPath();
192205
}
193206

194207
/**
@@ -224,7 +237,7 @@ protected function makeModelName($tableName)
224237
*
225238
* @return array
226239
*/
227-
abstract protected function getColumn();
240+
abstract protected function getColumns();
228241

229242
/**
230243
* Transfers every column in the giving array to a collection of fields.

src/Models/.php_cs.cache

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"php":"7.1.7","version":"2.7.0:v2.7.0#e4e93a120117e879cfc1f231fbf29274707cd834","rules":{"blank_line_after_namespace":true,"braces":true,"class_definition":true,"elseif":true,"function_declaration":true,"indentation_type":true,"line_ending":true,"lowercase_constants":true,"lowercase_keywords":true,"method_argument_space":{"ensure_fully_multiline":true},"no_break_comment":true,"no_closing_tag":true,"no_spaces_after_function_name":true,"no_spaces_inside_parenthesis":true,"no_trailing_whitespace":true,"no_trailing_whitespace_in_comment":true,"single_blank_line_at_eof":true,"single_class_element_per_statement":{"elements":["property"]},"single_import_per_statement":true,"single_line_after_imports":true,"switch_case_semicolon_to_colon":true,"switch_case_space":true,"visibility_required":true,"encoding":true,"full_opening_tag":true},"hashes":{"Resource.php":1548729220}}

0 commit comments

Comments
 (0)