-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathBeanDescriptor.php
More file actions
1782 lines (1555 loc) · 70.8 KB
/
BeanDescriptor.php
File metadata and controls
1782 lines (1555 loc) · 70.8 KB
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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace TheCodingMachine\TDBM\Utils;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\Index;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
use Doctrine\DBAL\Types\Type;
use JsonSerializable;
use Mouf\Database\SchemaAnalyzer\SchemaAnalyzer;
use PhpParser\Comment\Doc;
use Ramsey\Uuid\Uuid;
use TheCodingMachine\TDBM\AbstractTDBMObject;
use TheCodingMachine\TDBM\AlterableResultIterator;
use TheCodingMachine\TDBM\ConfigurationInterface;
use TheCodingMachine\TDBM\InnerResultIterator;
use TheCodingMachine\TDBM\ResultIterator;
use TheCodingMachine\TDBM\SafeFunctions;
use TheCodingMachine\TDBM\Schema\ForeignKey;
use TheCodingMachine\TDBM\Schema\ForeignKeys;
use TheCodingMachine\TDBM\TDBMException;
use TheCodingMachine\TDBM\TDBMSchemaAnalyzer;
use TheCodingMachine\TDBM\TDBMService;
use TheCodingMachine\TDBM\Utils\Annotation\AbstractTraitAnnotation;
use TheCodingMachine\TDBM\Utils\Annotation\AddInterfaceOnDao;
use TheCodingMachine\TDBM\Utils\Annotation\AddTrait;
use TheCodingMachine\TDBM\Utils\Annotation\AddTraitOnDao;
use TheCodingMachine\TDBM\Utils\Annotation\AnnotationParser;
use TheCodingMachine\TDBM\Utils\Annotation\AddInterface;
use Laminas\Code\Generator\AbstractMemberGenerator;
use Laminas\Code\Generator\ClassGenerator;
use Laminas\Code\Generator\DocBlock\Tag;
use Laminas\Code\Generator\DocBlock\Tag\GenericTag;
use Laminas\Code\Generator\DocBlock\Tag\ParamTag;
use Laminas\Code\Generator\DocBlock\Tag\ReturnTag;
use Laminas\Code\Generator\DocBlock\Tag\ThrowsTag;
use Laminas\Code\Generator\DocBlock\Tag\VarTag;
use Laminas\Code\Generator\DocBlockGenerator;
use Laminas\Code\Generator\FileGenerator;
use Laminas\Code\Generator\MethodGenerator;
use Laminas\Code\Generator\ParameterGenerator;
use Laminas\Code\Generator\PropertyGenerator;
use function implode;
use function strtolower;
use function var_export;
/**
* This class represents a bean.
*/
class BeanDescriptor implements BeanDescriptorInterface
{
/**
* @var Table
*/
private $table;
/**
* @var SchemaAnalyzer
*/
private $schemaAnalyzer;
/**
* @var Schema
*/
private $schema;
/**
* @var AbstractBeanPropertyDescriptor[]
*/
private $beanPropertyDescriptors = [];
/**
* @var TDBMSchemaAnalyzer
*/
private $tdbmSchemaAnalyzer;
/**
* @var NamingStrategyInterface
*/
private $namingStrategy;
/**
* @var string
*/
private $beanNamespace;
/**
* @var string
*/
private $generatedBeanNamespace;
/**
* @var AnnotationParser
*/
private $annotationParser;
/**
* @var string
*/
private $daoNamespace;
/**
* @var string
*/
private $generatedDaoNamespace;
/**
* @var string
*/
private $resultIteratorNamespace;
/**
* @var string
*/
private $generatedResultIteratorNamespace;
/**
* @var CodeGeneratorListenerInterface
*/
private $codeGeneratorListener;
/**
* @var ConfigurationInterface
*/
private $configuration;
/**
* @var BeanRegistry
*/
private $registry;
/**
* @var MethodDescriptorInterface[][]
*/
private $descriptorsByMethodName = [];
/**
* @var DirectForeignKeyMethodDescriptor[]|null
*/
private $directForeignKeysDescriptors = null;
/**
* @var PivotTableMethodsDescriptor[]|null
*/
private $pivotTableDescriptors = null;
public function __construct(
Table $table,
string $beanNamespace,
string $generatedBeanNamespace,
string $daoNamespace,
string $generatedDaoNamespace,
string $resultIteratorNamespace,
string $generatedResultIteratorNamespace,
SchemaAnalyzer $schemaAnalyzer,
Schema $schema,
TDBMSchemaAnalyzer $tdbmSchemaAnalyzer,
NamingStrategyInterface $namingStrategy,
AnnotationParser $annotationParser,
CodeGeneratorListenerInterface $codeGeneratorListener,
ConfigurationInterface $configuration,
BeanRegistry $registry
) {
$this->table = $table;
$this->beanNamespace = $beanNamespace;
$this->generatedBeanNamespace = $generatedBeanNamespace;
$this->daoNamespace = $daoNamespace;
$this->generatedDaoNamespace = $generatedDaoNamespace;
$this->resultIteratorNamespace = $resultIteratorNamespace;
$this->generatedResultIteratorNamespace = $generatedResultIteratorNamespace;
$this->schemaAnalyzer = $schemaAnalyzer;
$this->schema = $schema;
$this->tdbmSchemaAnalyzer = $tdbmSchemaAnalyzer;
$this->namingStrategy = $namingStrategy;
$this->annotationParser = $annotationParser;
$this->codeGeneratorListener = $codeGeneratorListener;
$this->configuration = $configuration;
$this->registry = $registry;
}
public function initBeanPropertyDescriptors(): void
{
$this->beanPropertyDescriptors = $this->getProperties($this->table);
//init the list of method names with regular properties names
foreach ($this->beanPropertyDescriptors as $beanPropertyDescriptor) {
$this->checkForDuplicate($beanPropertyDescriptor);
}
}
/**
* Returns the foreign-key the column is part of, if any. null otherwise.
*
* @param Table $table
* @param Column $column
*
* @return ForeignKeyConstraint|null
*/
private function isPartOfForeignKey(Table $table, Column $column): ?ForeignKeyConstraint
{
$localColumnName = $column->getName();
foreach ($table->getForeignKeys() as $foreignKey) {
foreach ($foreignKey->getUnquotedLocalColumns() as $columnName) {
if ($columnName === $localColumnName) {
return $foreignKey;
}
}
}
return null;
}
/**
* @return AbstractBeanPropertyDescriptor[]
*/
public function getBeanPropertyDescriptors(): array
{
return $this->beanPropertyDescriptors;
}
/**
* Returns the list of columns that are not nullable and not autogenerated for a given table and its parent.
*
* @return AbstractBeanPropertyDescriptor[]
*/
public function getConstructorProperties(): array
{
$constructorProperties = array_filter($this->beanPropertyDescriptors, static function (AbstractBeanPropertyDescriptor $property) {
return !$property instanceof InheritanceReferencePropertyDescriptor && $property->isCompulsory() && !$property->isReadOnly();
});
return $constructorProperties;
}
/**
* Returns the list of columns that have default values for a given table.
*
* @return AbstractBeanPropertyDescriptor[]
*/
public function getPropertiesWithDefault(): array
{
$properties = $this->getPropertiesForTable($this->table);
$defaultProperties = array_filter($properties, function (AbstractBeanPropertyDescriptor $property) {
return $property->hasDefault();
});
return $defaultProperties;
}
/**
* Returns the list of properties exposed as getters and setters in this class.
*
* @return AbstractBeanPropertyDescriptor[]
*/
public function getExposedProperties(): array
{
$exposedProperties = array_filter($this->beanPropertyDescriptors, function (AbstractBeanPropertyDescriptor $property) {
return !$property instanceof InheritanceReferencePropertyDescriptor && $property->getTable()->getName() === $this->table->getName();
});
return $exposedProperties;
}
/**
* Returns the list of properties for this table (including parent tables).
*
* @param Table $table
*
* @return AbstractBeanPropertyDescriptor[]
*/
private function getProperties(Table $table): array
{
// Security check: a table MUST have a primary key
TDBMDaoGenerator::getPrimaryKeyColumnsOrFail($table);
$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
if ($parentRelationship) {
$parentTable = $this->schema->getTable($parentRelationship->getForeignTableName());
$properties = $this->getProperties($parentTable);
// we merge properties by overriding property names.
$localProperties = $this->getPropertiesForTable($table);
foreach ($localProperties as $name => $property) {
// We do not override properties if this is a primary key!
if (!$property instanceof InheritanceReferencePropertyDescriptor && $property->isPrimaryKey()) {
continue;
}
$properties[$name] = $property;
}
} else {
$properties = $this->getPropertiesForTable($table);
}
return $properties;
}
/**
* Returns the list of properties for this table (ignoring parent tables).
*
* @param Table $table
*
* @return AbstractBeanPropertyDescriptor[]
*/
private function getPropertiesForTable(Table $table): array
{
$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
if ($parentRelationship) {
$ignoreColumns = $parentRelationship->getUnquotedForeignColumns();
} else {
$ignoreColumns = [];
}
$beanPropertyDescriptors = [];
foreach ($table->getColumns() as $column) {
if (in_array($column->getName(), $ignoreColumns, true)) {
continue;
}
$fk = $this->isPartOfForeignKey($table, $column);
if ($fk !== null) {
// Check that previously added descriptors are not added on same FK (can happen with multi key FK).
foreach ($beanPropertyDescriptors as $beanDescriptor) {
if ($beanDescriptor instanceof ObjectBeanPropertyDescriptor && $beanDescriptor->getForeignKey() === $fk) {
continue 2;
}
}
$propertyDescriptor = new ObjectBeanPropertyDescriptor($table, $fk, $this->namingStrategy, $this->beanNamespace, $this->annotationParser, $this->registry->getBeanForTableName($fk->getForeignTableName()), $this->resultIteratorNamespace);
// Check that this property is not an inheritance relationship
$parentRelationship = $this->schemaAnalyzer->getParentRelationship($table->getName());
if ($parentRelationship !== null && $parentRelationship->getName() === $fk->getName()) {
$beanPropertyDescriptors[] = new InheritanceReferencePropertyDescriptor(
$table,
$column,
$this->namingStrategy,
$this->annotationParser,
$propertyDescriptor
);
} else {
$beanPropertyDescriptors[] = $propertyDescriptor;
}
} else {
$beanPropertyDescriptors[] = new ScalarBeanPropertyDescriptor($table, $column, $this->namingStrategy, $this->annotationParser);
}
}
// Now, let's get the name of all properties and let's check there is no duplicate.
/* @var $names AbstractBeanPropertyDescriptor[] */
$names = [];
foreach ($beanPropertyDescriptors as $beanDescriptor) {
$name = $beanDescriptor->getGetterName();
if (isset($names[$name])) {
$names[$name]->useAlternativeName();
$beanDescriptor->useAlternativeName();
} else {
$names[$name] = $beanDescriptor;
}
}
// Final check (throw exceptions if problem arises)
$names = [];
foreach ($beanPropertyDescriptors as $beanDescriptor) {
$name = $beanDescriptor->getGetterName();
if (isset($names[$name])) {
throw new TDBMException('Unsolvable name conflict while generating method name "' . $name . '"');
} else {
$names[$name] = $beanDescriptor;
}
}
// Last step, let's rebuild the list with a map:
$beanPropertyDescriptorsMap = [];
foreach ($beanPropertyDescriptors as $beanDescriptor) {
$beanPropertyDescriptorsMap[$beanDescriptor->getVariableName()] = $beanDescriptor;
}
return $beanPropertyDescriptorsMap;
}
private function generateBeanConstructor(): MethodGenerator
{
$constructorProperties = $this->getConstructorProperties();
$constructor = new MethodGenerator('__construct', [], MethodGenerator::FLAG_PUBLIC);
$constructorDocBlock = new DocBlockGenerator('The constructor takes all compulsory arguments.');
$constructorDocBlock->setWordWrap(false);
$constructor->setDocBlock($constructorDocBlock);
$assigns = [];
$parentConstructorArguments = [];
foreach ($constructorProperties as $property) {
$parameter = new ParameterGenerator(ltrim($property->getSafeVariableName(), '$'));
if ($property->isTypeHintable()) {
$parameter->setType($property->getPhpType());
}
$constructor->setParameter($parameter);
$constructorDocBlock->setTag($property->getParamAnnotation());
if ($property->getTable()->getName() === $this->table->getName()) {
$assigns[] = $property->getConstructorAssignCode()."\n";
} else {
$parentConstructorArguments[] = $property->getSafeVariableName();
}
}
$parentConstructorCode = sprintf("parent::__construct(%s);\n", implode(', ', $parentConstructorArguments));
foreach ($this->getPropertiesWithDefault() as $property) {
$assigns[] = $property->assignToDefaultCode()."\n";
}
$body = $parentConstructorCode . implode('', $assigns);
$constructor->setBody($body);
return $constructor;
}
/**
* Returns the descriptors of one-to-many relationships (the foreign keys pointing on this beans)
*
* @return DirectForeignKeyMethodDescriptor[]
*/
private function getDirectForeignKeysDescriptors(): array
{
if ($this->directForeignKeysDescriptors !== null) {
return $this->directForeignKeysDescriptors;
}
$fks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($this->table->getName());
$descriptors = [];
foreach ($fks as $fk) {
$desc = new DirectForeignKeyMethodDescriptor($fk, $this->table, $this->namingStrategy, $this->annotationParser, $this->beanNamespace, $this->resultIteratorNamespace);
$this->checkForDuplicate($desc);
$descriptors[] = $desc;
}
$this->directForeignKeysDescriptors = $descriptors;
return $this->directForeignKeysDescriptors;
}
/**
* @return PivotTableMethodsDescriptor[]
*/
private function getPivotTableDescriptors(): array
{
if ($this->pivotTableDescriptors !== null) {
return $this->pivotTableDescriptors;
}
$descs = [];
foreach ($this->schemaAnalyzer->detectJunctionTables(true) as $table) {
// There are exactly 2 FKs since this is a pivot table.
$fks = array_values($table->getForeignKeys());
if ($fks[0]->getForeignTableName() === $this->table->getName()) {
list($localFk, $remoteFk) = $fks;
$desc = new PivotTableMethodsDescriptor($table, $localFk, $remoteFk, $this->namingStrategy, $this->annotationParser, $this->beanNamespace, $this->resultIteratorNamespace);
$this->checkForDuplicate($desc);
$descs[] = $desc;
}
if ($fks[1]->getForeignTableName() === $this->table->getName()) {
list($remoteFk, $localFk) = $fks;
$desc = new PivotTableMethodsDescriptor($table, $localFk, $remoteFk, $this->namingStrategy, $this->annotationParser, $this->beanNamespace, $this->resultIteratorNamespace);
$this->checkForDuplicate($desc);
$descs[] = $desc;
}
}
$this->pivotTableDescriptors = $descs;
return $this->pivotTableDescriptors;
}
/**
* Check the method name isn't already used and flag the associated descriptors to use their alternative names if it is the case
*/
private function checkForDuplicate(MethodDescriptorInterface $descriptor): void
{
$name = strtolower($descriptor->getName());
if (!isset($this->descriptorsByMethodName[$name])) {
$this->descriptorsByMethodName[$name] = [];
}
$this->descriptorsByMethodName[$name][] = $descriptor;
$descriptors = $this->descriptorsByMethodName[$name];
if (count($descriptors) > 1) {
$properties = array_filter($descriptors, function ($descriptor) {
return $descriptor instanceof AbstractBeanPropertyDescriptor;
});
$renameProperties = count($properties) > 1;
foreach ($descriptors as $descriptor) {
if ($renameProperties || !$descriptor instanceof AbstractBeanPropertyDescriptor) {
$descriptor->useAlternativeName();
}
}
}
}
/**
* Returns the list of method descriptors (and applies the alternative name if needed).
*
* @return RelationshipMethodDescriptorInterface[]
*/
public function getMethodDescriptors(): array
{
$directForeignKeyDescriptors = $this->getDirectForeignKeysDescriptors();
$pivotTableDescriptors = $this->getPivotTableDescriptors();
return array_merge($directForeignKeyDescriptors, $pivotTableDescriptors);
}
public function generateJsonSerialize(): MethodGenerator
{
$tableName = $this->table->getName();
$parentFk = $this->schemaAnalyzer->getParentRelationship($tableName);
$method = new MethodGenerator('jsonSerialize');
$method->setDocBlock(new DocBlockGenerator(
'Serializes the object for JSON encoding.',
null,
[
new ParamTag('$stopRecursion', ['bool'], 'Parameter used internally by TDBM to stop embedded objects from embedding other objects.'),
new ReturnTag(['array'])
]
));
$method->setParameter(new ParameterGenerator('stopRecursion', 'bool', false));
/*
* Set jsonSerialize's mixed return type for php >= 8
*/
if (version_compare(PHP_VERSION, '8.0.0', '>=')) {
$method->setReturnType("mixed");
}
if ($parentFk !== null) {
$body = '$array = parent::jsonSerialize($stopRecursion);';
} else {
$body = '$array = [];';
}
foreach ($this->getExposedProperties() as $beanPropertyDescriptor) {
$propertyCode = $beanPropertyDescriptor->getJsonSerializeCode();
if (!empty($propertyCode)) {
$body .= PHP_EOL . $propertyCode;
}
}
// Many2many relationships
foreach ($this->getMethodDescriptors() as $methodDescriptor) {
$methodCode = $methodDescriptor->getJsonSerializeCode();
if (!empty($methodCode)) {
$body .= PHP_EOL . $methodCode;
}
}
$body .= PHP_EOL . 'return $array;';
$method->setBody($body);
return $method;
}
/**
* Returns as an array the class we need to extend from and the list of use statements.
*
* @param ForeignKeyConstraint|null $parentFk
* @return string[]
*/
private function generateExtendsAndUseStatements(ForeignKeyConstraint $parentFk = null): array
{
$classes = [];
if ($parentFk !== null) {
$extends = $this->namingStrategy->getBeanClassName($parentFk->getForeignTableName());
$classes[] = $extends;
}
foreach ($this->getBeanPropertyDescriptors() as $beanPropertyDescriptor) {
$className = $beanPropertyDescriptor->getClassName();
if (null !== $className) {
$classes[] = $className;
}
}
foreach ($this->getMethodDescriptors() as $descriptor) {
$classes = array_merge($classes, $descriptor->getUsedClasses());
}
$classes = array_unique($classes);
return $classes;
}
/**
* Returns the representation of the PHP bean file with all getters and setters.
*
* @return ?FileGenerator
*/
public function generatePhpCode(): ?FileGenerator
{
$file = new FileGenerator();
$class = new ClassGenerator();
$class->setAbstract(true);
$file->setClass($class);
$file->setNamespace($this->generatedBeanNamespace);
$tableName = $this->table->getName();
$baseClassName = $this->namingStrategy->getBaseBeanClassName($tableName);
$className = $this->namingStrategy->getBeanClassName($tableName);
$parentFk = $this->schemaAnalyzer->getParentRelationship($this->table->getName());
$classes = $this->generateExtendsAndUseStatements($parentFk);
foreach ($classes as $useClass) {
$file->setUse($this->beanNamespace.'\\'.$useClass);
}
/*$uses = array_map(function ($className) {
return 'use '.$this->beanNamespace.'\\'.$className.";\n";
}, $classes);
$use = implode('', $uses);*/
$extends = $this->getExtendedBeanClassName();
if ($extends === null) {
$class->setExtendedClass(AbstractTDBMObject::class);
$file->setUse(AbstractTDBMObject::class);
} else {
/** @var class-string $extends */
$class->setExtendedClass($extends);
}
$file->setUse(ResultIterator::class);
$file->setUse(AlterableResultIterator::class);
$file->setUse(Uuid::class);
$file->setUse(JsonSerializable::class);
$file->setUse(ForeignKeys::class);
$class->setName($baseClassName);
$file->setDocBlock(new DocBlockGenerator(
'This file has been automatically generated by TDBM.',
<<<EOF
DO NOT edit this file, as it might be overwritten.
If you need to perform changes, edit the $className class instead!
EOF
));
$class->setDocBlock(new DocBlockGenerator("The $baseClassName class maps the '$tableName' table in database."));
/** @var AddInterface[] $addInterfaceAnnotations */
$addInterfaceAnnotations = $this->annotationParser->getTableAnnotations($this->table)->findAnnotations(AddInterface::class);
$interfaces = [ JsonSerializable::class ];
foreach ($addInterfaceAnnotations as $annotation) {
/** @phpstan-var class-string $className */
$className = $annotation->getName();
$interfaces[] = $className;
}
$class->setImplementedInterfaces($interfaces);
$this->registerTraits($class, AddTrait::class);
$method = $this->generateBeanConstructor();
$method = $this->codeGeneratorListener->onBaseBeanConstructorGenerated($method, $this, $this->configuration, $class);
if ($method) {
$class->addMethodFromGenerator($this->generateBeanConstructor());
}
$fks = [];
foreach ($this->getExposedProperties() as $property) {
if ($property instanceof ObjectBeanPropertyDescriptor) {
$fks[] = $property->getForeignKey();
}
[$getter, $setter] = $property->getGetterSetterCode();
[$getter, $setter] = $this->codeGeneratorListener->onBaseBeanPropertyGenerated($getter, $setter, $property, $this, $this->configuration, $class);
if ($getter !== null) {
$class->addMethodFromGenerator($getter);
}
if ($setter !== null) {
$class->addMethodFromGenerator($setter);
}
}
$pivotTableMethodsDescriptors = [];
foreach ($this->getMethodDescriptors() as $methodDescriptor) {
if ($methodDescriptor instanceof DirectForeignKeyMethodDescriptor) {
[$method] = $methodDescriptor->getCode();
$method = $this->codeGeneratorListener->onBaseBeanOneToManyGenerated($method, $methodDescriptor, $this, $this->configuration, $class);
if ($method) {
$class->addMethodFromGenerator($method);
}
} elseif ($methodDescriptor instanceof PivotTableMethodsDescriptor) {
$pivotTableMethodsDescriptors[] = $methodDescriptor;
[ $getter, $adder, $remover, $has, $setter ] = $methodDescriptor->getCode();
$methods = $this->codeGeneratorListener->onBaseBeanManyToManyGenerated($getter, $adder, $remover, $has, $setter, $methodDescriptor, $this, $this->configuration, $class);
foreach ($methods as $method) {
if ($method) {
$class->addMethodFromGenerator($method);
}
}
} else {
throw new \RuntimeException('Unexpected instance'); // @codeCoverageIgnore
}
}
$manyToManyRelationshipCode = $this->generateGetManyToManyRelationshipDescriptorCode($pivotTableMethodsDescriptors);
if ($manyToManyRelationshipCode !== null) {
$class->addMethodFromGenerator($manyToManyRelationshipCode);
}
$manyToManyRelationshipKeysCode = $this->generateGetManyToManyRelationshipDescriptorKeysCode($pivotTableMethodsDescriptors);
if ($manyToManyRelationshipKeysCode !== null) {
$class->addMethodFromGenerator($manyToManyRelationshipKeysCode);
}
$foreignKeysProperty = new PropertyGenerator('foreignKeys');
$foreignKeysProperty->setStatic(true);
$foreignKeysProperty->setVisibility(AbstractMemberGenerator::VISIBILITY_PRIVATE);
$foreignKeysProperty->setDocBlock(new DocBlockGenerator(null, null, [new VarTag(null, ['\\'.ForeignKeys::class])]));
$class->addPropertyFromGenerator($foreignKeysProperty);
$method = $this->generateGetForeignKeys($fks);
$class->addMethodFromGenerator($method);
$method = $this->generateJsonSerialize();
$method = $this->codeGeneratorListener->onBaseBeanJsonSerializeGenerated($method, $this, $this->configuration, $class);
if ($method !== null) {
$class->addMethodFromGenerator($method);
}
$class->addMethodFromGenerator($this->generateGetUsedTablesCode());
$onDeleteCode = $this->generateOnDeleteCode();
if ($onDeleteCode) {
$class->addMethodFromGenerator($onDeleteCode);
}
$cloneCode = $this->generateCloneCode($pivotTableMethodsDescriptors);
$cloneCode = $this->codeGeneratorListener->onBaseBeanCloneGenerated($cloneCode, $this, $this->configuration, $class);
if ($cloneCode) {
$class->addMethodFromGenerator($cloneCode);
}
$file = $this->codeGeneratorListener->onBaseBeanGenerated($file, $this, $this->configuration);
return $file;
}
private function registerTraits(ClassGenerator $class, string $annotationClass): void
{
/** @var AbstractTraitAnnotation[] $addTraitAnnotations */
$addTraitAnnotations = $this->annotationParser->getTableAnnotations($this->table)->findAnnotations($annotationClass);
foreach ($addTraitAnnotations as $annotation) {
$class->addTrait($annotation->getName());
}
foreach ($addTraitAnnotations as $annotation) {
foreach ($annotation->getInsteadOf() as $method => $replacedTrait) {
$class->addTraitOverride($method, $replacedTrait);
}
foreach ($annotation->getAs() as $method => $replacedMethod) {
$class->addTraitAlias($method, $replacedMethod);
}
}
}
/**
* Writes the representation of the PHP DAO file.
*
* @return ?FileGenerator
*/
public function generateDaoPhpCode(): ?FileGenerator
{
$file = new FileGenerator();
$class = new ClassGenerator();
$class->setAbstract(true);
$file->setClass($class);
$file->setNamespace($this->generatedDaoNamespace);
$tableName = $this->table->getName();
$primaryKeyColumns = TDBMDaoGenerator::getPrimaryKeyColumnsOrFail($this->table);
list($defaultSort, $defaultSortDirection) = $this->getDefaultSortColumnFromAnnotation($this->table);
$className = $this->namingStrategy->getDaoClassName($tableName);
$baseClassName = $this->namingStrategy->getBaseDaoClassName($tableName);
$beanClassWithoutNameSpace = $this->namingStrategy->getBeanClassName($tableName);
$beanClassName = $this->beanNamespace.'\\'.$beanClassWithoutNameSpace;
$resultIteratorClassWithoutNameSpace = $this->getResultIteratorClassName();
$resultIteratorClass = $this->resultIteratorNamespace.'\\'.$resultIteratorClassWithoutNameSpace;
$findByDaoCodeMethods = $this->generateFindByDaoCode($this->beanNamespace, $beanClassWithoutNameSpace, $class);
$usedBeans[] = $beanClassName;
// Let's suppress duplicates in used beans (if any)
$usedBeans = array_flip(array_flip($usedBeans));
foreach ($usedBeans as $usedBean) {
$class->addUse($usedBean);
}
$file->setDocBlock(new DocBlockGenerator(
<<<EOF
This file has been automatically generated by TDBM.
DO NOT edit this file, as it might be overwritten.
If you need to perform changes, edit the $className class instead!
EOF
));
$file->setNamespace($this->generatedDaoNamespace);
$class->addUse(TDBMService::class);
$class->addUse(ResultIterator::class);
$class->addUse(TDBMException::class);
$class->setName($baseClassName);
$class->setDocBlock(new DocBlockGenerator("The $baseClassName class will maintain the persistence of $beanClassWithoutNameSpace class into the $tableName table."));
/** @var AddInterfaceOnDao[] $addInterfaceOnDaoAnnotations */
$addInterfaceOnDaoAnnotations = $this->annotationParser->getTableAnnotations($this->table)->findAnnotations(AddInterfaceOnDao::class);
$interfaces = [];
foreach ($addInterfaceOnDaoAnnotations as $annotation) {
/** @phpstan-var class-string $className */
$className = $annotation->getName();
$interfaces[] = $className;
}
$class->setImplementedInterfaces($interfaces);
$this->registerTraits($class, AddTraitOnDao::class);
$tdbmServiceProperty = new PropertyGenerator('tdbmService');
$tdbmServiceProperty->setDocBlock(new DocBlockGenerator(null, null, [new VarTag(null, ['\\'.TDBMService::class])]));
$class->addPropertyFromGenerator($tdbmServiceProperty);
$defaultSortProperty = new PropertyGenerator('defaultSort', $defaultSort);
$defaultSortProperty->setDocBlock(new DocBlockGenerator('The default sort column.', null, [new VarTag(null, ['string', 'null'])]));
$class->addPropertyFromGenerator($defaultSortProperty);
$defaultSortPropertyDirection = new PropertyGenerator('defaultDirection', $defaultSort && $defaultSortDirection ? $defaultSortDirection : 'asc');
$defaultSortPropertyDirection->setDocBlock(new DocBlockGenerator('The default sort direction.', null, [new VarTag(null, ['string'])]));
$class->addPropertyFromGenerator($defaultSortPropertyDirection);
$constructorMethod = new MethodGenerator(
'__construct',
[ new ParameterGenerator('tdbmService', TDBMService::class) ],
MethodGenerator::FLAG_PUBLIC,
'$this->tdbmService = $tdbmService;',
'Sets the TDBM service used by this DAO.'
);
$constructorMethod = $this->codeGeneratorListener->onBaseDaoConstructorGenerated($constructorMethod, $this, $this->configuration, $class);
if ($constructorMethod !== null) {
$class->addMethodFromGenerator($constructorMethod);
}
$saveMethod = new MethodGenerator(
'save',
[ new ParameterGenerator('obj', $beanClassName) ],
MethodGenerator::FLAG_PUBLIC,
'$this->tdbmService->save($obj);',
(new DocBlockGenerator(
"Persist the $beanClassWithoutNameSpace instance.",
null,
[
new ParamTag('obj', [$beanClassWithoutNameSpace], 'The bean to save.')
]
))->setWordWrap(false)
);
$saveMethod->setReturnType('void');
$saveMethod = $this->codeGeneratorListener->onBaseDaoSaveGenerated($saveMethod, $this, $this->configuration, $class);
if ($saveMethod !== null) {
$class->addMethodFromGenerator($saveMethod);
}
$findAllBody = <<<EOF
if (\$this->defaultSort) {
\$orderBy = '$tableName.'.\$this->defaultSort.' '.\$this->defaultDirection;
} else {
\$orderBy = null;
}
return \$this->tdbmService->findObjects('$tableName', null, [], \$orderBy, [], null, \\$beanClassName::class, \\$resultIteratorClass::class);
EOF;
$findAllMethod = new MethodGenerator(
'findAll',
[],
MethodGenerator::FLAG_PUBLIC,
$findAllBody,
(new DocBlockGenerator("Get all $beanClassWithoutNameSpace records."))->setWordWrap(false)
);
$findAllMethod->setReturnType($resultIteratorClass);
$findAllMethod = $this->codeGeneratorListener->onBaseDaoFindAllGenerated($findAllMethod, $this, $this->configuration, $class);
if ($findAllMethod !== null) {
$class->addMethodFromGenerator($findAllMethod);
}
if (count($primaryKeyColumns) > 0) {
$lazyLoadingParameterName = 'lazyLoading';
$parameters = [];
$parametersTag = [];
$primaryKeyFilter = [];
foreach ($primaryKeyColumns as $primaryKeyColumn) {
if ($primaryKeyColumn === $lazyLoadingParameterName) {
throw new TDBMException('Primary Column name `' . $lazyLoadingParameterName . '` is not allowed.');
}
$phpType = TDBMDaoGenerator::dbalTypeToPhpType($this->table->getColumn($primaryKeyColumn)->getType());
$parameters[] = new ParameterGenerator($primaryKeyColumn, $phpType);
$parametersTag[] = new ParamTag($primaryKeyColumn, [$phpType]);
$primaryKeyFilter[] = "'$primaryKeyColumn' => \$$primaryKeyColumn";
}
$parameters[] = new ParameterGenerator($lazyLoadingParameterName, 'bool', false);
$parametersTag[] = new ParamTag($lazyLoadingParameterName, ['bool'], 'If set to true, the object will not be loaded right away. Instead, it will be loaded when you first try to access a method of the object.');
$parametersTag[] = new ReturnTag(['\\'.$beanClassName]);
$parametersTag[] = new ThrowsTag('\\'.TDBMException::class);
$getByIdMethod = new MethodGenerator(
'getById',
$parameters,
MethodGenerator::FLAG_PUBLIC,
"return \$this->tdbmService->findObjectByPk('$tableName', [" . implode(', ', $primaryKeyFilter) . "], [], \$$lazyLoadingParameterName, \\$beanClassName::class, \\$resultIteratorClass::class);",
(new DocBlockGenerator(
"Get $beanClassWithoutNameSpace specified by its ID (its primary key).",
'If the primary key does not exist, an exception is thrown.',
$parametersTag
))->setWordWrap(false)
);
$getByIdMethod->setReturnType($beanClassName);
$getByIdMethod = $this->codeGeneratorListener->onBaseDaoGetByIdGenerated($getByIdMethod, $this, $this->configuration, $class);
if ($getByIdMethod) {
$class->addMethodFromGenerator($getByIdMethod);
}
}
$deleteMethodBody = <<<EOF
if (\$cascade === true) {
\$this->tdbmService->deleteCascade(\$obj);
} else {
\$this->tdbmService->delete(\$obj);
}
EOF;
$deleteMethod = new MethodGenerator(
'delete',
[
new ParameterGenerator('obj', $beanClassName),
new ParameterGenerator('cascade', 'bool', false)
],
MethodGenerator::FLAG_PUBLIC,
$deleteMethodBody,
(new DocBlockGenerator(
"Get all $beanClassWithoutNameSpace records.",
null,
[
new ParamTag('obj', ['\\'.$beanClassName], 'The object to delete'),
new ParamTag('cascade', ['bool'], 'If true, it will delete all objects linked to $obj'),
]
))->setWordWrap(false)
);
$deleteMethod->setReturnType('void');
$deleteMethod = $this->codeGeneratorListener->onBaseDaoDeleteGenerated($deleteMethod, $this, $this->configuration, $class);
if ($deleteMethod !== null) {
$class->addMethodFromGenerator($deleteMethod);
}
$findMethodBody = <<<EOF
if (\$this->defaultSort && \$orderBy == null) {
\$orderBy = '$tableName.'.\$this->defaultSort.' '.\$this->defaultDirection;
}
return \$this->tdbmService->findObjects('$tableName', \$filter, \$parameters, \$orderBy, \$additionalTablesFetch, \$mode, \\$beanClassName::class, \\$resultIteratorClass::class);
EOF;
$findMethod = new MethodGenerator(
'find',
[
(new ParameterGenerator('filter'))->setDefaultValue(null),
new ParameterGenerator('parameters', 'array', []),
(new ParameterGenerator('orderBy'))->setDefaultValue(null),
new ParameterGenerator('additionalTablesFetch', 'array', []),
(new ParameterGenerator('mode', '?int'))->setDefaultValue(null),
],
MethodGenerator::FLAG_PROTECTED,
$findMethodBody,
(new DocBlockGenerator(
"Get all $beanClassWithoutNameSpace records.",
null,
[
new ParamTag('filter', ['mixed'], 'The filter bag (see TDBMService::findObjects for complete description)'),
new ParamTag('parameters', ['mixed[]'], 'The parameters associated with the filter'),
new ParamTag('orderBy', ['mixed'], 'The order string'),
new ParamTag('additionalTablesFetch', ['string[]'], 'A list of additional tables to fetch (for performance improvement)'),
new ParamTag('mode', ['int', 'null'], 'Either TDBMService::MODE_ARRAY or TDBMService::MODE_CURSOR (for large datasets). Defaults to TDBMService::MODE_ARRAY.')
]
))->setWordWrap(false)
);
$findMethod->setReturnType($resultIteratorClass);
$findMethod = $this->codeGeneratorListener->onBaseDaoFindGenerated($findMethod, $this, $this->configuration, $class);
if ($findMethod !== null) {
$class->addMethodFromGenerator($findMethod);
}
$findFromSqlMethodBody = <<<EOF
if (\$this->defaultSort && \$orderBy == null) {
\$orderBy = '$tableName.'.\$this->defaultSort.' '.\$this->defaultDirection;
}