-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathGenerator.php
861 lines (743 loc) · 29.6 KB
/
Generator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
<?php
/**
* @link http://www.phundament.com
*
* @copyright Copyright (c) 2014 herzog kommunikation GmbH
* @license http://www.phundament.com/license/
*/
namespace schmunk42\giiant\generators\model;
use schmunk42\giiant\helpers\SaveForm;
use Yii;
use yii\gii\CodeFile;
use yii\helpers\Inflector;
use yii\helpers\StringHelper;
/**
* This generator will generate one or multiple ActiveRecord classes for the specified database table.
*
* @author Tobias Munk <[email protected]>
*
* @since 0.0.1
*/
class Generator extends \yii\gii\generators\model\Generator
{
/**
* @var bool whether to overwrite (extended) model classes, will be always created, if file does not exist
*/
public $generateModelClass = false;
/**
* @var string base-traits
*/
public $baseTraits = null;
/**
* @var null string for the table prefix, which is ignored in generated class name
*/
public $tablePrefix = null;
/**
* @var bool whether or not to use BlameableBehavior
*/
public $useBlameableBehavior = true;
/**
* @var string the name of the column where the user who created the entry is stored
*/
public $createdByColumn = 'created_by';
/**
* @var string the name of the column where the user who updated the entry is stored
*/
public $updatedByColumn = 'updated_by';
/**
* @var bool whether or not to use TimestampBehavior
*/
public $useTimestampBehavior = true;
/**
* @var string support user custom TimestampBehavior class
*/
public $timestampBehaviorClass = 'yii\behaviors\TimestampBehavior';
/**
* @var string the name of the column where the user who updated the entry is stored
*/
public $createdAtColumn = 'created_at';
/**
* @var string the name of the column where the user who updated the entry is stored
*/
public $updatedAtColumn = 'updated_at';
/**
* @var bool whether or not to use 2amigos/yii2-translateable-behavior
*/
public $useTranslatableBehavior = true;
/**
* @var string the name of the table containing the translations. {{table}} will be replaced with the value in
* "Table Name" field
*/
public $languageTableName = '{{table}}_lang';
/**
* @var string the column name where the language code is stored
*/
public $languageCodeColumn = 'language';
/**
* @var string prefix to prepend to the base model, setting "Base" will result in a model named "BasePost"
*/
public $baseClassPrefix = '';
/**
* @var string prefix to prepend to the many many relation methods
*/
public $manyManyRelationSuffix = '';
/**
* @var string suffix to append to the base model, setting "Base" will result in a model named "PostBase"
*/
public $baseClassSuffix = '';
/**
* @var bool whether to enable or disable the pluralization of the models name
*/
public $disablePluralization = false;
/**
* @var array key-value pairs for mapping a table-name to class-name, eg. 'prefix_FOObar' => 'FooBar'
*/
public $tableNameMap = [];
public $singularEntities = false;
public $removeDuplicateRelations = false;
/** @var bool Cache relations data between model generation */
public $cacheRelationsData = true;
/**
* @var bool This indicates whether the generator should generate attribute hints by using the comments of the corresponding DB columns
*/
public $generateHintsFromComments = true;
/**
* @var string form field for selecting and loading saved gii forms
*/
public $savedForm;
public $messageCategory = 'models';
public $giiInfoPath = '.gii';
protected $classNames2;
protected static $_relationsCache = null;
/**
* the names given here are used as suffixes to the base_translation table name, eg.
*
* $languageTableName = '{table}_translation';
* $translationTableAdditions = ['meta'];
*
* will process {table}_translation AND {table}_translation_meta
*
* to be able to set the 'fallbackLanguage' flag fot the behaviour of this translation, items can be arrays like:
*
* $translationTableAdditions = ['name' => 'meta', 'fallbackLanguage' => false]
*
* if fallbackLanguage is not specified, 'true' is used as default
*
* @var array af additional translation tables
*/
public $translationTableAdditions = ['name' => 'meta', 'fallbackLanguage' => false];
/**
* {@inheritdoc}
*/
public function getName()
{
return 'Giiant Model';
}
/**
* {@inheritdoc}
*/
public function getDescription()
{
return 'This generator generates an ActiveRecord class and base class for the specified database table.';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return array_merge(
parent::rules(),
[
[
[
'generateModelClass',
'useTranslatableBehavior',
'generateHintsFromComments',
'useBlameableBehavior',
'useTimestampBehavior',
'singularEntities',
],
'boolean'
],
[
[
'languageTableName',
'languageCodeColumn',
'createdByColumn',
'updatedByColumn',
'createdAtColumn',
'updatedAtColumn',
'savedForm',
'timestampBehaviorClass'
],
'string'
],
[['tablePrefix'], 'safe'],
]
);
}
/**
* all form fields for saving in saved forms.
*
* @return array
*/
public function formAttributes()
{
return [
'tableName',
'tablePrefix',
'modelClass',
'ns',
'baseClass',
'db',
'generateRelations',
'generateJunctionRelationMode',
'generateRelationsFromCurrentSchema',
'generateLabelsFromComments',
'generateHintsFromComments',
'generateModelClass',
'generateQuery',
'queryNs',
'queryClass',
'queryBaseClass',
'enableI18N',
'singularEntities',
'messageCategory',
'useTranslatableBehavior',
'languageTableName',
'languageCodeColumn',
'useBlameableBehavior',
'createdByColumn',
'updatedByColumn',
'useTimestampBehavior',
'createdAtColumn',
'updatedAtColumn',
'timestampBehaviorClass',
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return array_merge(
parent::attributeLabels(),
[
'generateModelClass' => 'Generate Model Class',
'generateHintsFromComments' => 'Generate Hints from DB Comments',
]
);
}
/**
* {@inheritdoc}
*/
public function hints()
{
return array_merge(
parent::hints(),
[
'generateModelClass' => 'This indicates whether the generator should generate the model class, this should usually be done only once. The model-base class is always generated.',
'tablePrefix' => 'Custom table prefix, eg <code>app_</code>.<br/><b>Note!</b> overrides <code>yii\db\Connection</code> prefix!',
'useTranslatableBehavior' => 'Use <code>2amigos/yii2-translateable-behavior</code> for tables with a relation to a translation table.',
'languageTableName' => 'The name of the table containing the translations. <code>{{table}}</code> will be replaced with the value in "Table Name" field.',
'languageCodeColumn' => 'The column name where the language code is stored.',
'generateHintsFromComments' => 'This indicates whether the generator should generate attribute hints
by using the comments of the corresponding DB columns.',
'useTimestampBehavior' => 'Use <code>TimestampBehavior</code> for tables with column(s) for created at and/or updated at timestamps.',
'timestampBehaviorClass' => 'Use custom TimestampBehavior class.',
'createdAtColumn' => 'The column name where the created at timestamp is stored.',
'updatedAtColumn' => 'The column name where the updated at timestamp is stored.',
'useBlameableBehavior' => 'Use <code>BlameableBehavior</code> for tables with column(s) for created by and/or updated by user IDs.',
'createdByColumn' => "The column name where the record creator's user ID is stored.",
'updatedByColumn' => "The column name where the record updater's user ID is stored.",
],
SaveForm::hint()
);
}
/**
* {@inheritdoc}
*/
public function requiredTemplates()
{
return ['model.php', 'model-extended.php'];
}
/**
* {@inheritdoc}
*/
public function generate()
{
$files = [];
if ($this->cacheRelationsData) {
if (static::$_relationsCache === null) {
static::$_relationsCache = $this->generateRelations();
}
$relations = static::$_relationsCache;
} else {
$relations = $this->generateRelations();
}
$db = $this->getDbConnection();
$generateTranslationTrait = false;
foreach ($this->getTableNames() as $tableName) {
list($relations, $translations) = array_values($this->extractTranslations($tableName, $relations));
$className = $this->modelClass === '' || php_sapi_name() === 'cli'
? $this->generateClassName($tableName)
: $this->modelClass;
$queryClassName = ($this->generateQuery) ? $this->generateQueryClassName($className) : false;
$tableSchema = $db->getTableSchema($tableName);
$params = [
'tableName' => $tableName,
'className' => $className,
'queryClassName' => $queryClassName,
'tableSchema' => $tableSchema,
'labels' => $this->generateLabels($tableSchema),
'hints' => $this->generateHints($tableSchema),
'rules' => $this->generateRules($tableSchema),
'relations' => $relations[$tableName] ?? [],
'ns' => $this->ns,
'enum' => $this->getEnum($tableSchema->columns),
'traits' => (array)$this->baseTraits
];
if (!empty($translations)) {
$params['translation'] = $translations;
$params['traits'][] = '\\' . $this->ns . '\traits\TranslationAttributeRules';
$generateTranslationTrait = true;
}
$params['blameable'] = $this->generateBlameable($tableSchema);
$params['timestamp'] = $this->generateTimestamp($tableSchema);
$files[] = new CodeFile(
Yii::getAlias(
'@' . str_replace('\\', '/', $this->ns)
) . '/base/' . $this->baseClassPrefix . $className . $this->baseClassSuffix . '.php',
$this->render('model.php', $params)
);
$modelClassFile = Yii::getAlias('@' . str_replace('\\', '/', $this->ns)) . '/' . $className . '.php';
if ($this->generateModelClass || !is_file($modelClassFile)) {
$files[] = new CodeFile(
$modelClassFile,
$this->render('model-extended.php', $params)
);
}
if ($queryClassName) {
$queryClassFile = Yii::getAlias(
'@' . str_replace('\\', '/', $this->queryNs)
) . '/' . $queryClassName . '.php';
if ($this->generateModelClass || !is_file($queryClassFile)) {
$params = [
'className' => $queryClassName,
'modelClassName' => $className,
];
$files[] = new CodeFile(
$queryClassFile,
$this->render('query.php', $params)
);
}
}
/*
* create gii/[name]GiiantModel.json with actual form data
*/
$suffix = str_replace(' ', '', $this->getName());
$formDataDir = Yii::getAlias('@' . str_replace('\\', '/', $this->ns));
$formDataFile = StringHelper::dirname($formDataDir)
. '/' . $this->giiInfoPath . '/'
. '/' . $tableName . $suffix . '.json';
$generatorForm = (clone $this);
$generatorForm->tableName = $tableName;
$generatorForm->modelClass = $className;
$formData = json_encode(SaveForm::getFormAttributesValues($generatorForm, $this->formAttributes()),
JSON_PRETTY_PRINT);
$files[] = new CodeFile($formDataFile, $formData);
}
if ($generateTranslationTrait) {
$files[] = new CodeFile(
Yii::getAlias('@' . str_replace('\\', '/', $this->ns)) . '/traits/TranslationAttributeRules.php',
$this->render('translation-trait.php', [
'ns' => $this->ns . '\traits'
])
);
}
return $files;
}
/**
* Generates a class name from the specified table name.
*
* @param string $tableName the table name (which may contain schema prefix)
*
* @return string the generated class name
*/
public function generateClassName($tableName, $useSchemaName = null)
{
//Yii::trace("Generating class name for '{$tableName}'...", __METHOD__);
if (isset($this->classNames2[$tableName])) {
//Yii::trace("Using '{$this->classNames2[$tableName]}' for '{$tableName}' from classNames2.", __METHOD__);
return $this->classNames2[$tableName];
}
if (isset($this->tableNameMap[$tableName])) {
Yii::trace("Converted '{$tableName}' from tableNameMap.", __METHOD__);
return $this->classNames2[$tableName] = $this->tableNameMap[$tableName];
}
if (($pos = strrpos($tableName, '.')) !== false) {
$tableName = substr($tableName, $pos + 1);
}
$db = $this->getDbConnection();
$patterns = [];
$patterns[] = "/^{$this->tablePrefix}(.*?)$/";
$patterns[] = "/^(.*?){$this->tablePrefix}$/";
$patterns[] = "/^{$db->tablePrefix}(.*?)$/";
$patterns[] = "/^(.*?){$db->tablePrefix}$/";
if (strpos((string)$this->tableName, '*') !== false) {
$pattern = $this->tableName;
if (($pos = strrpos($pattern, '.')) !== false) {
$pattern = substr($pattern, $pos + 1);
}
$patterns[] = '/^' . str_replace('*', '(\w+)', $pattern) . '$/';
}
$className = $tableName;
foreach ($patterns as $pattern) {
if (preg_match($pattern, $tableName, $matches)) {
$className = $matches[1];
Yii::trace("Mapping '{$tableName}' to '{$className}' from pattern '{$pattern}'.", __METHOD__);
break;
}
}
$returnName = Inflector::id2camel($className, '_');
if ($this->singularEntities) {
$returnName = Inflector::singularize($returnName);
}
Yii::trace("Converted '{$tableName}' to '{$returnName}'.", __METHOD__);
return $this->classNames2[$tableName] = $returnName;
}
/**
* Generates the attribute hints for the specified table.
*
* @param \yii\db\TableSchema $table the table schema
*
* @return array the generated attribute hints (name => hint)
* or an empty array if $this->generateHintsFromComments is false
*/
public function generateHints($table)
{
$hints = [];
if ($this->generateHintsFromComments) {
foreach ($table->columns as $column) {
if (!empty($column->comment)) {
$hints[$column->name] = $column->comment;
}
}
}
return $hints;
}
/**
* {@inheritdoc}
*/
public function generateRelationName($relations, $table, $key, $multiple)
{
$suffix = '';
if ($this->disablePluralization) {
if ($multiple) {
$suffix = $this->manyManyRelationSuffix;
}
$multiple = false;
}
$relationName = parent::generateRelationName($relations, $table, $key, $multiple);
return $relationName . $suffix;
}
protected function generateRelations()
{
$relations = parent::generateRelations();
// inject namespace
$ns = "\\{$this->ns}\\";
foreach ($relations as $model => $relInfo) {
foreach ($relInfo as $relName => $relData) {
// removed duplicated relations, eg. klientai, klientai0
if ($this->removeDuplicateRelations && is_numeric(substr($relName, -1))) {
unset($relations[$model][$relName]);
continue;
}
$relations[$model][$relName][0] = preg_replace(
'/(has[A-Za-z0-9]+\()([a-zA-Z0-9]+::)/',
'$1__NS__$2',
$relations[$model][$relName][0]
);
$relations[$model][$relName][0] = str_replace('__NS__', $ns, $relations[$model][$relName][0]);
}
}
return $relations;
}
/**
* prepare ENUM field values.
*
* @param array $columns
*
* @return array
*/
public function getEnum($columns)
{
$enum = [];
foreach ($columns as $column) {
if (!$this->isEnum($column)) {
continue;
}
$column_camel_name = str_replace(' ', '', ucwords(implode(' ', explode('_', $column->name))));
$enum[$column->name]['func_opts_name'] = 'opts' . $column_camel_name;
$enum[$column->name]['func_get_label_name'] = 'get' . $column_camel_name . 'ValueLabel';
$enum[$column->name]['values'] = [];
$enum_values = explode(',', substr($column->dbType, 4, strlen($column->dbType) - 1));
foreach ($enum_values as $value) {
$value = trim($value, "()'");
$const_name = strtoupper($column->name . '_' . $value);
$const_name = preg_replace('/\s+/', '_', $const_name);
$const_name = str_replace(['-', '_', ' '], '_', $const_name);
$const_name = preg_replace('/[^A-Z0-9_]/', '', $const_name);
$label = Inflector::camel2words($value);
$enum[$column->name]['values'][] = [
'value' => $value,
'const_name' => $const_name,
'label' => $label,
];
}
}
return $enum;
}
/**
* validate is ENUM.
*
* @param $column table column
*
* @return type
*/
public function isEnum($column)
{
return substr(strtoupper($column->dbType), 0, 4) == 'ENUM';
}
/**
* Generates validation rules for the specified table and add enum value validation.
*
* @param \yii\db\TableSchema $table the table schema
*
* @return array the generated validation rules
*/
public function generateRules($table)
{
$columns = [];
foreach ($table->columns as $index => $column) {
$isBlameableCol = ($column->name === $this->createdByColumn || $column->name === $this->updatedByColumn);
$isTimestampCol = ($column->name === $this->createdAtColumn || $column->name === $this->updatedAtColumn);
$removeCol = ($this->useBlameableBehavior && $isBlameableCol)
|| ($this->useTimestampBehavior && $isTimestampCol);
if ($removeCol) {
$columns[$index] = $column;
unset($table->columns[$index]);
}
}
$rules = [];
//for enum fields create rules "in range" for all enum values
$enum = $this->getEnum($table->columns);
foreach ($enum as $field_name => $field_details) {
$ea = array();
foreach ($field_details['values'] as $field_enum_values) {
$ea[] = 'self::' . $field_enum_values['const_name'];
}
$rules[] = "['" . $field_name . "', 'in', 'range' => [\n " . implode(
",\n ",
$ea
) . ",\n ]\n ]";
}
// inject namespace for targetClass
$parentRules = parent::generateRules($table);
$ns = "\\{$this->ns}\\";
$match = "'targetClass' => ";
$replace = $match . $ns;
$replaceMap = [
[
'search' => "'targetClass' => ",
'replace' => "'targetClass' => " . $ns,
],
[
'search' => "'unique', ",
'replace' => "'unique', 'targetClass' => " . $ns . $this->modelClass . '::class, ',
]
];
foreach ($parentRules as $k => $parentRule) {
foreach ($replaceMap as $replaceItem) {
$parentRules[$k] = str_replace($replaceItem['search'], $replaceItem['replace'], $parentRule);
break;
}
}
$rules = array_merge($parentRules, $rules);
$table->columns = array_merge($table->columns, $columns);
return $rules;
}
/**
* @return \yii\db\Connection the DB connection from the DI container or as application component specified by [[db]]
*/
protected function getDbConnection()
{
if (Yii::$container->has($this->db)) {
return Yii::$container->get($this->db);
} else {
return Yii::$app->get($this->db);
}
}
/**
* Validates the [[db]] attribute.
*/
public function validateDb()
{
if (Yii::$container->has($this->db)) {
return;
}
parent::validateDb();
}
/**
* {@inheritdoc}
*/
public function getTableNames()
{
return parent::getTableNames();
}
/**
* @return array associative array containing the extracted relations and the modified translations (from parent) + translations_meta fields if exists
*/
protected function extractTranslations($tableName, $relations) {
$translations = [
'relations' => $relations,
'translations' => [],
];
# check if we have base translations
$baseTranslations = $this->extractBaseTranslations($tableName, $relations);
// we do not want timestamp columns as translatable fields
$unsetFields = [$this->createdAtColumn, $this->updatedAtColumn, $this->createdByColumn, $this->updatedByColumn];
if (!empty($baseTranslations['translations']['fields'])) {
$translations = $baseTranslations;
$translations['translations']['fields'] = array_diff($baseTranslations['translations']['fields'], $unsetFields);
}
$baseLanguageTableName = $this->languageTableName;
foreach ($this->translationTableAdditions as $addition) {
if (is_array($addition)) {
$additionName = $addition['name'];
$additionFallbackLanguage = $addition['fallbackLanguage'] ?? true;
} else {
$additionName = $addition;
$additionFallbackLanguage = true;
}
# in the following runs we must use possibly modified relations from previous extractTranslations() call
$prevRelations = $translations['relations'];
# to be able to reuse extractTranslations() set $this->languageTableName for one method call
$this->languageTableName .= '_' . $additionName;
# here we must use possibly modified relations from previous extractTranslations() call
$additionTranslations = $this->extractBaseTranslations($tableName, $prevRelations);
# if we get meta-translations fields, overwrite relations,
# otherwise we get the relation as <table_name>TranslationMetas and translationMetas
if (!empty($additionTranslations['translations']['fields'])) {
$translations['relations'] = $additionTranslations['relations'];
$translations['translations']['additions'][$additionName]['fields'] = array_diff($additionTranslations['translations']['fields'], $unsetFields);
$translations['translations']['additions'][$additionName]['code'] = $additionTranslations['translations']['code'];
# set flag if this addition should use the fallback language feature
$translations['translations']['additions'][$additionName]['fallbackLanguage'] = $additionFallbackLanguage;
}
# reset languageTableName to default value (without prefix)
$this->languageTableName = $baseLanguageTableName;
}
return $translations;
}
/**
* @param array $relations All database's relations
*
* @return array associative array containing the extracted relations and the modified translations
*/
protected function extractBaseTranslations($tableName, $relations)
{
$langTableName = str_replace('{{table}}', $tableName, $this->languageTableName);
if ($this->useTranslatableBehavior and isset($relations[$langTableName], $relations[$tableName])) {
$db = $this->getDbConnection();
$langTableSchema = $db->getTableSchema($langTableName);
$langTableColumns = $langTableSchema->getColumnNames();
$langTableKeys = array_merge(
$langTableSchema->primaryKey,
array_map(
function ($fk) {
return array_keys($fk)[1];
},
$langTableSchema->foreignKeys
)
);
$langClassName = $this->generateClassName($langTableName);
foreach ($relations[$tableName] as $relationName => $relation) {
list($code, $referencedClassName) = $relation;
if ($referencedClassName === $langClassName) {
// found relation from model to modelLang.
// collect fields which are not PK, FK nor language code
$fields = [];
foreach ($langTableColumns as $columnName) {
if (!in_array($columnName, $langTableKeys) and strcasecmp(
$columnName,
$this->languageCodeColumn
) !== 0
) {
$fields[] = $columnName;
}
}
unset($relations[$tableName][$relationName]);
return [
'relations' => $relations,
'translations' => [
'fields' => $fields,
'code' => $code,
'language_table' => $langTableName,
'language_table_pk' => $langTableSchema->primaryKey,
],
];
}
}
}
return [
'relations' => $relations,
'translations' => [],
];
}
/**
* @param \yii\db\TableSchema $table the table schema
*
* @return string[]
*/
protected function generateBlameable($table)
{
$createdBy = $table->getColumn($this->createdByColumn) !== null ? $this->createdByColumn : false;
$updatedBy = $table->getColumn($this->updatedByColumn) !== null ? $this->updatedByColumn : false;
if ($this->useBlameableBehavior && ($createdBy || $updatedBy)) {
return [
'createdByAttribute' => $createdBy,
'updatedByAttribute' => $updatedBy,
];
}
return [];
}
/**
* @param \yii\db\TableSchema $table the table schema
*
* @return string[]
*/
protected function generateTimestamp($table)
{
$createdAt = $table->getColumn($this->createdAtColumn) !== null ? $this->createdAtColumn : false;
$updatedAt = $table->getColumn($this->updatedAtColumn) !== null ? $this->updatedAtColumn : false;
#var_dump($table->getColumn($this->createdAtColumn)); exit;
if ($this->useTimestampBehavior && ($createdAt || $updatedAt)) {
// check column type, if datetime set NOW() as Value
if ($table->getColumn($this->createdAtColumn)->type === 'datetime') {
return [
'value' => '(new \DateTime())->format(\'Y-m-d H:i:s\')',
'createdAtAttribute' => $createdAt,
'updatedAtAttribute' => $updatedAt,
'timestampBehaviorClass' => $this->timestampBehaviorClass,
];
}
return [
'createdAtAttribute' => $createdAt,
'updatedAtAttribute' => $updatedAt,
'timestampBehaviorClass' => $this->timestampBehaviorClass,
];
}
return [];
}
}