/
QueryBuilder.php
2008 lines (1825 loc) · 73.9 KB
/
QueryBuilder.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
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
/**
* This file is part of the Propel package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
namespace Propel\Generator\Builder\Om;
use Propel\Generator\Model\Column;
use Propel\Generator\Model\CrossForeignKeys;
use Propel\Generator\Model\ForeignKey;
use Propel\Generator\Model\PropelTypes;
use Propel\Generator\Model\Table;
/**
* Generates a PHP5 base Query class for user object model (OM).
*
* This class produces the base query class (e.g. BaseBookQuery) which contains
* all the custom-built query methods.
*
* @author Francois Zaninotto
*/
class QueryBuilder extends AbstractOMBuilder
{
/**
* Returns the package for the [base] object classes.
*
* @return string
*/
public function getPackage()
{
return parent::getPackage() . '.Base';
}
/**
* Returns the namepace for the query object classes.
*
* @return string
*/
public function getNamespace()
{
if ($namespace = parent::getNamespace()) {
return $namespace . '\\Base';
}
return 'Base';
}
/**
* Returns the name of the current class being built.
* @return string
*/
public function getUnprefixedClassName()
{
return $this->getStubQueryBuilder()->getUnprefixedClassName();
}
/**
* Returns parent class name that extends TableQuery Object if is set this class must extends ModelCriteria for be compatible
* @return string
*/
public function getParentClass()
{
$parentClass = $this->getBehaviorContent('parentClass');
return null === $parentClass ? ($this->getTable()->getBaseQueryClass() != "" ? $this->getTable()->getBaseQueryClass() : 'ModelCriteria') : $parentClass;
}
/**
* Adds class phpdoc comment and opening of class.
* @param string &$script The script will be modified in this method.
*/
protected function addClassOpen(&$script)
{
$table = $this->getTable();
$tableName = $table->getName();
$tableDesc = $table->getDescription();
$queryClass = $this->getQueryClassName();
$modelClass = $this->getObjectClassName();
$parentClass = $this->getParentClass();
$script .= "
/**
* Base class that represents a query for the '$tableName' table.
*
* $tableDesc
*";
if ($this->getBuildProperty('generator.objectModel.addTimeStamp')) {
$now = strftime('%c');
$script .= "
* This class was autogenerated by Propel " . $this->getBuildProperty('general.version') . " on:
*
* $now
*";
}
// magic orderBy() methods, for IDE completion
foreach ($this->getTable()->getColumns() as $column) {
$script .= "
* @method $queryClass orderBy" . $column->getPhpName() . "(\$order = Criteria::ASC) Order by the " . $column->getName() . " column";
}
$script .= "
*";
// magic groupBy() methods, for IDE completion
foreach ($this->getTable()->getColumns() as $column) {
$script .= "
* @method $queryClass groupBy" . $column->getPhpName() . "() Group by the " . $column->getName() . " column";
}
// override the signature of ModelCriteria::left-, right- and innerJoin to specify the class of the returned object, for IDE completion
$script .= "
*
* @method $queryClass leftJoin(\$relation) Adds a LEFT JOIN clause to the query
* @method $queryClass rightJoin(\$relation) Adds a RIGHT JOIN clause to the query
* @method $queryClass innerJoin(\$relation) Adds a INNER JOIN clause to the query
*";
$script .= "
* @method $queryClass leftJoinWith(\$relation) Adds a LEFT JOIN clause and with to the query
* @method $queryClass rightJoinWith(\$relation) Adds a RIGHT JOIN clause and with to the query
* @method $queryClass innerJoinWith(\$relation) Adds a INNER JOIN clause and with to the query
*";
$relationQueryClasses = [];
// magic XXXjoinYYY() methods, for IDE completion
foreach ($this->getTable()->getForeignKeys() as $fk) {
$relationName = $this->getFKPhpNameAffix($fk);
$script .= "
* @method $queryClass leftJoin" . $relationName . "(\$relationAlias = null) Adds a LEFT JOIN clause to the query using the " . $relationName . " relation
* @method $queryClass rightJoin" . $relationName . "(\$relationAlias = null) Adds a RIGHT JOIN clause to the query using the " . $relationName . " relation
* @method $queryClass innerJoin" . $relationName . "(\$relationAlias = null) Adds a INNER JOIN clause to the query using the " . $relationName . " relation
*";
$script .= "
* @method $queryClass joinWith" . $relationName . "(\$joinType = Criteria::INNER_JOIN) Adds a join clause and with to the query using the " . $relationName . " relation
*";
$script .= "
* @method $queryClass leftJoinWith" . $relationName . "() Adds a LEFT JOIN clause and with to the query using the " . $relationName . " relation
* @method $queryClass rightJoinWith" . $relationName . "() Adds a RIGHT JOIN clause and with to the query using the " . $relationName . " relation
* @method $queryClass innerJoinWith" . $relationName . "() Adds a INNER JOIN clause and with to the query using the " . $relationName . " relation
*";
$relationQueryClasses[$this->getNewStubQueryBuilder($fk->getForeignTable())->getQueryClassName(true)] = true;
}
foreach ($this->getTable()->getReferrers() as $refFK) {
$relationName = $this->getRefFKPhpNameAffix($refFK);
$script .= "
* @method $queryClass leftJoin" . $relationName . "(\$relationAlias = null) Adds a LEFT JOIN clause to the query using the " . $relationName . " relation
* @method $queryClass rightJoin" . $relationName . "(\$relationAlias = null) Adds a RIGHT JOIN clause to the query using the " . $relationName . " relation
* @method $queryClass innerJoin" . $relationName . "(\$relationAlias = null) Adds a INNER JOIN clause to the query using the " . $relationName . " relation
*";
$script .= "
* @method $queryClass joinWith" . $relationName . "(\$joinType = Criteria::INNER_JOIN) Adds a join clause and with to the query using the " . $relationName . " relation
*";
$script .= "
* @method $queryClass leftJoinWith" . $relationName . "() Adds a LEFT JOIN clause and with to the query using the " . $relationName . " relation
* @method $queryClass rightJoinWith" . $relationName . "() Adds a RIGHT JOIN clause and with to the query using the " . $relationName . " relation
* @method $queryClass innerJoinWith" . $relationName . "() Adds a INNER JOIN clause and with to the query using the " . $relationName . " relation
*";
$relationQueryClasses[$this->getNewStubQueryBuilder($refFK->getTable())->getQueryClassName(true)] = true;
}
if (!empty($relationQueryClasses)) {
$relationQueryClasses = implode('|', array_keys($relationQueryClasses));
$script .= "
* @method $relationQueryClasses endUse() Finalizes a secondary criteria and merges it with its primary Criteria
*";
}
// override the signature of ModelCriteria::findOne() to specify the class of the returned object, for IDE completion
$script .= "
* @method $modelClass findOne(ConnectionInterface \$con = null) Return the first $modelClass matching the query
* @method $modelClass findOneOrCreate(ConnectionInterface \$con = null) Return the first $modelClass matching the query, or a new $modelClass object populated from the query conditions when no match is found
*";
// magic findBy() methods, for IDE completion
foreach ($this->getTable()->getColumns() as $column) {
$script .= "
* @method $modelClass findOneBy" . $column->getPhpName() . "(" . $column->getPhpType() . " \$" . $column->getName() . ") Return the first $modelClass filtered by the " . $column->getName() . " column";
}
$script .= " * \n";
// override the signature of ModelCriteria::require*() to specify the class of the returned object, for IDE completion
$script .= "
* @method $modelClass requirePk(\$key, ConnectionInterface \$con = null) Return the $modelClass by primary key and throws {$this->getEntityNotFoundExceptionClass()} when not found
* @method $modelClass requireOne(ConnectionInterface \$con = null) Return the first $modelClass matching the query and throws {$this->getEntityNotFoundExceptionClass()} when not found
*";
// magic requireOneBy() methods, for IDE completion
foreach ($this->getTable()->getColumns() as $column) {
$script .= "
* @method $modelClass requireOneBy" . $column->getPhpName() . "(" . $column->getPhpType() . " \$" . $column->getName() . ") Return the first $modelClass filtered by the " . $column->getName() . " column and throws {$this->getEntityNotFoundExceptionClass()} when not found";
}
$script .= "
*
* @method {$modelClass}[]|ObjectCollection find(ConnectionInterface \$con = null) Return $modelClass objects based on current ModelCriteria";
foreach ($this->getTable()->getColumns() as $column) {
$script .= "
* @method {$modelClass}[]|ObjectCollection findBy" . $column->getPhpName() . "(" . $column->getPhpType() . " \$" . $column->getName() . ") Return $modelClass objects filtered by the " . $column->getName() . " column";
}
$script .= "
* @method {$modelClass}[]|\\Propel\\Runtime\\Util\\PropelModelPager paginate(\$page = 1, \$maxPerPage = 10, ConnectionInterface \$con = null) Issue a SELECT query based on the current ModelCriteria and uses a page and a maximum number of results per page to compute an offset and a limit
*
*/
abstract class ".$this->getUnqualifiedClassName()." extends " . $parentClass . "
{
";
}
/**
* Specifies the methods that are added as part of the stub object class.
*
* By default there are no methods for the empty stub classes; override this method
* if you want to change that behavior.
*
* @see ObjectBuilder::addClassBody()
*/
protected function addClassBody(&$script)
{
$table = $this->getTable();
// namespaces
$this->declareClasses(
'\Propel\Runtime\Propel',
'\Propel\Runtime\ActiveQuery\ModelCriteria',
'\Propel\Runtime\ActiveQuery\Criteria',
'\Propel\Runtime\ActiveQuery\ModelJoin',
'\Exception',
'\Propel\Runtime\Exception\PropelException'
);
$this->declareClassFromBuilder($this->getStubQueryBuilder(), 'Child');
$this->declareClassFromBuilder($this->getTableMapBuilder());
// apply behaviors
$this->applyBehaviorModifier('queryAttributes', $script, " ");
$this->addEntityNotFoundExceptionClass($script);
$this->addConstructor($script);
$this->addFactory($script);
$this->addFindPk($script);
$this->addFindPkSimple($script);
$this->addFindPkComplex($script);
$this->addFindPks($script);
$this->addFilterByPrimaryKey($script);
$this->addFilterByPrimaryKeys($script);
foreach ($this->getTable()->getColumns() as $col) {
$this->addFilterByCol($script, $col);
if ($col->isNamePlural()) {
if ($col->getType() === PropelTypes::PHP_ARRAY) {
$this->addFilterByArrayCol($script, $col);
} elseif ($col->isSetType()) {
$this->addFilterBySetCol($script, $col);
}
}
}
foreach ($this->getTable()->getForeignKeys() as $fk) {
$this->addFilterByFK($script, $fk);
$this->addJoinFk($script, $fk);
$this->addUseFKQuery($script, $fk);
}
foreach ($this->getTable()->getReferrers() as $refFK) {
$this->addFilterByRefFK($script, $refFK);
$this->addJoinRefFk($script, $refFK);
$this->addUseRefFKQuery($script, $refFK);
}
foreach ($this->getTable()->getCrossFks() as $crossFKs) {
$this->addFilterByCrossFK($script, $crossFKs);
}
$this->addPrune($script);
$this->addBasePreSelect($script);
$this->addBasePreDelete($script);
$this->addBasePostDelete($script);
$this->addBasePreUpdate($script);
$this->addBasePostUpdate($script);
// add the insert, update, delete, etc. methods
if (!$table->isAlias() && !$table->isReadOnly()) {
$this->addDeleteMethods($script);
}
// apply behaviors
$this->applyBehaviorModifier('staticConstants', $script, " ");
$this->applyBehaviorModifier('staticAttributes', $script, " ");
$this->applyBehaviorModifier('staticMethods', $script, " ");
$this->applyBehaviorModifier('queryMethods', $script, " ");
}
/**
* Adds the entityNotFoundExceptionClass property which is necessary for the `requireOne` method
* of the `ModelCriteria`
*/
protected function addEntityNotFoundExceptionClass(&$script)
{
$script .= "protected \$entityNotFoundExceptionClass = '" . addslashes($this->getEntityNotFoundExceptionClass()) . "';\n";
}
private function getEntityNotFoundExceptionClass()
{
return $this->getBuildProperty('generator.objectModel.entityNotFoundExceptionClass');
}
/**
* Adds the doDeleteAll(), etc. methods.
* @param string &$script The script will be modified in this method.
*/
protected function addDeleteMethods(&$script)
{
$this->addDoDeleteAll($script);
$this->addDelete($script);
if ($this->isDeleteCascadeEmulationNeeded()) {
$this->addDoOnDeleteCascade($script);
}
if ($this->isDeleteSetNullEmulationNeeded()) {
$this->addDoOnDeleteSetNull($script);
}
}
/**
* Whether the platform in use requires ON DELETE CASCADE emulation and whether there are references to this table.
* @return boolean
*/
protected function isDeleteCascadeEmulationNeeded()
{
$table = $this->getTable();
if ((!$this->getPlatform()->supportsNativeDeleteTrigger() || $this->getBuildProperty('generator.objectModel.emulateForeignKeyConstraints')) && count($table->getReferrers()) > 0) {
foreach ($table->getReferrers() as $fk) {
if ( ForeignKey::CASCADE === $fk->getOnDelete()) {
return true;
}
}
}
return false;
}
/**
* Whether the platform in use requires ON DELETE SETNULL emulation and whether there are references to this table.
* @return boolean
*/
protected function isDeleteSetNullEmulationNeeded()
{
$table = $this->getTable();
if ((!$this->getPlatform()->supportsNativeDeleteTrigger() || $this->getBuildProperty('generator.objectModel.emulateForeignKeyConstraints')) && count($table->getReferrers()) > 0) {
foreach ($table->getReferrers() as $fk) {
if (ForeignKey::SETNULL === $fk->getOnDelete()) {
return true;
}
}
}
return false;
}
/**
* Closes class.
* @param string &$script The script will be modified in this method.
*/
protected function addClassClose(&$script)
{
$script .= "
} // " . $this->getUnqualifiedClassName() . "
";
$this->applyBehaviorModifier('queryFilter', $script, "");
}
/**
* Adds the constructor for this object.
* @param string &$script The script will be modified in this method.
* @see addConstructor()
*/
protected function addConstructor(&$script)
{
$this->addConstructorComment($script);
$this->addConstructorOpen($script);
$this->addConstructorBody($script);
$this->addConstructorClose($script);
}
/**
* Adds the comment for the constructor
* @param string &$script The script will be modified in this method.
**/
protected function addConstructorComment(&$script)
{
$script .= "
/**
* Initializes internal state of ".$this->getClassName()." object.
*
* @param string \$dbName The database name
* @param string \$modelName The phpName of a model, e.g. 'Book'
* @param string \$modelAlias The alias for the model in this query, e.g. 'b'
*/";
}
/**
* Adds the function declaration for the constructor
* @param string &$script The script will be modified in this method.
**/
protected function addConstructorOpen(&$script)
{
$table = $this->getTable();
$script .= "
public function __construct(\$dbName = '" . $table->getDatabase()->getName() . "', \$modelName = '" . addslashes($this->getNewStubObjectBuilder($table)->getFullyQualifiedClassName()) . "', \$modelAlias = null)
{";
}
/**
* Adds the function body for the constructor
* @param string &$script The script will be modified in this method.
**/
protected function addConstructorBody(&$script)
{
$script .= "
parent::__construct(\$dbName, \$modelName, \$modelAlias);";
}
/**
* Adds the function close for the constructor
* @param string &$script The script will be modified in this method.
**/
protected function addConstructorClose(&$script)
{
$script .= "
}
";
}
/**
* Adds the factory for this object.
* @param string &$script The script will be modified in this method.
*/
protected function addFactory(&$script)
{
$this->addFactoryComment($script);
$this->addFactoryOpen($script);
$this->addFactoryBody($script);
$this->addFactoryClose($script);
}
/**
* Adds the comment for the factory
* @param string &$script The script will be modified in this method.
**/
protected function addFactoryComment(&$script)
{
$classname = $this->getClassNameFromBuilder($this->getNewStubQueryBuilder($this->getTable()));
$script .= "
/**
* Returns a new " . $classname . " object.
*
* @param string \$modelAlias The alias of a model in the query
* @param Criteria \$criteria Optional Criteria to build the query from
*
* @return " . $classname . "
*/";
}
/**
* Adds the function declaration for the factory
* @param string &$script The script will be modified in this method.
**/
protected function addFactoryOpen(&$script)
{
$script .= "
public static function create(\$modelAlias = null, Criteria \$criteria = null)
{";
}
/**
* Adds the function body for the factory
* @param string &$script The script will be modified in this method.
*/
protected function addFactoryBody(&$script)
{
$classname = $this->getClassNameFromBuilder($this->getNewStubQueryBuilder($this->getTable()));
$script .= "
if (\$criteria instanceof " . $classname . ") {
return \$criteria;
}
\$query = new " . $classname . "();
if (null !== \$modelAlias) {
\$query->setModelAlias(\$modelAlias);
}
if (\$criteria instanceof Criteria) {
\$query->mergeWith(\$criteria);
}
return \$query;";
}
/**
* Adds the function close for the factory
* @param string &$script The script will be modified in this method.
*/
protected function addFactoryClose(&$script)
{
$script .= "
}
";
}
protected function addFindPk(&$script)
{
$class = $this->getObjectClassName();
$tableMapClassName = $this->getTableMapClassName();
$table = $this->getTable();
$script .= "
/**
* Find object by primary key.
* Propel uses the instance pool to skip the database if the object exists.
* Go fast if the query is untouched.
*";
if ($table->hasCompositePrimaryKey()) {
$pks = $table->getPrimaryKey();
$examplePk = array_slice([12, 34, 56, 78, 91], 0, count($pks));
$colNames = [];
foreach ($pks as $col) {
$colNames[]= '$' . $col->getName();
}
$pkType = 'array['. join($colNames, ', ') . ']';
$script .= "
* <code>
* \$obj = \$c->findPk(array(" . join($examplePk, ', ') . "), \$con);";
} else {
$pkType = 'mixed';
$script .= "
* <code>
* \$obj = \$c->findPk(12, \$con);";
}
$script .= "
* </code>
*
* @param " . $pkType . " \$key Primary key to use for the query
* @param ConnectionInterface \$con an optional connection object
*
* @return $class|array|mixed the result, formatted by the current formatter
*/
public function findPk(\$key, ConnectionInterface \$con = null)
{";
if (!$table->hasPrimaryKey()) {
$this->declareClass('Propel\\Runtime\\Exception\\LogicException');
$script .= "
throw new LogicException('The {$this->getObjectName()} object has no primary key');
}
";
return $script;
}
$script .= "
if (\$key === null) {
return null;
}";
if ($table->hasCompositePrimaryKey()) {
$pks = [];
foreach ($table->getPrimaryKey() as $index => $column) {
$pks[] = "\$key[$index]";
}
} else {
$pks = '$key';
}
$pkHash = $this->getTableMapBuilder()->getInstancePoolKeySnippet($pks);
$script .= "
if (\$con === null) {
\$con = Propel::getServiceContainer()->getReadConnection({$this->getTableMapClass()}::DATABASE_NAME);
}
\$this->basePreSelect(\$con);
if (
\$this->formatter || \$this->modelAlias || \$this->with || \$this->select
|| \$this->selectColumns || \$this->asColumns || \$this->selectModifiers
|| \$this->map || \$this->having || \$this->joins
) {
return \$this->findPkComplex(\$key, \$con);
}
if ((null !== (\$obj = {$tableMapClassName}::getInstanceFromPool({$pkHash})))) {
// the object is already in the instance pool
return \$obj;
}
return \$this->findPkSimple(\$key, \$con);
}
";
}
protected function addFindPkSimple(&$script)
{
$table = $this->getTable();
// this method is not needed if the table has no primary key
if (!$table->hasPrimaryKey()) {
return '';
}
$platform = $this->getPlatform();
$tableMapClassName = $this->getTableMapClassName();
$ARClassName = $this->getObjectClassName();
$this->declareClassFromBuilder($this->getStubObjectBuilder());
$this->declareClasses('\PDO');
$selectColumns = [];
foreach ($table->getColumns() as $column) {
if (!$column->isLazyLoad()) {
$selectColumns []= $this->quoteIdentifier($column->getName());
}
}
$conditions = [];
foreach ($table->getPrimaryKey() as $index => $column) {
$conditions []= sprintf('%s = :p%d', $this->quoteIdentifier($column->getName()), $index);
}
$query = sprintf(
'SELECT %s FROM %s WHERE %s',
implode(', ', $selectColumns),
$this->quoteIdentifier($table->getName()),
implode(' AND ', $conditions)
);
$pks = [];
if ($table->hasCompositePrimaryKey()) {
foreach ($table->getPrimaryKey() as $index => $column) {
$pks []= "\$key[$index]";
}
} else {
$pks []= "\$key";
}
$pkHashFromRow = $this->getTableMapBuilder()->getInstancePoolKeySnippet($pks);
$script .= "
/**
* Find object by primary key using raw SQL to go fast.
* Bypass doSelect() and the object formatter by using generated code.
*
* @param mixed \$key Primary key to use for the query
* @param ConnectionInterface \$con A connection object
*
* @throws \\Propel\\Runtime\\Exception\\PropelException
*
* @return $ARClassName A model object, or null if the key is not found
*/
protected function findPkSimple(\$key, ConnectionInterface \$con)
{
\$sql = '$query';
try {
\$stmt = \$con->prepare(\$sql);";
if ($table->hasCompositePrimaryKey()) {
foreach ($table->getPrimaryKey() as $index => $column) {
$script .= $platform->getColumnBindingPHP($column, "':p$index'", "\$key[$index]", ' ');
}
} else {
$pk = $table->getPrimaryKey();
$column = $pk[0];
$script .= $platform->getColumnBindingPHP($column, "':p0'", "\$key", ' ');
}
$script .= "
\$stmt->execute();
} catch (Exception \$e) {
Propel::log(\$e->getMessage(), Propel::LOG_ERR);
throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', \$sql), 0, \$e);
}
\$obj = null;
if (\$row = \$stmt->fetch(\PDO::FETCH_NUM)) {";
if ($table->getChildrenColumn()) {
$script .="
\$cls = {$tableMapClassName}::getOMClass(\$row, 0, false);
/** @var $ARClassName \$obj */
\$obj = new \$cls();";
} else {
$script .="
/** @var $ARClassName \$obj */
\$obj = new $ARClassName();";
}
$script .= "
\$obj->hydrate(\$row);
{$tableMapClassName}::addInstanceToPool(\$obj, $pkHashFromRow);
}
\$stmt->closeCursor();
return \$obj;
}
";
}
/**
* Adds the findPk method for this object.
* @param string &$script The script will be modified in this method.
*/
protected function addFindPkComplex(&$script)
{
$class = $this->getObjectClassName();
$table = $this->getTable();
// this method is not needed if the table has no primary key
if (!$table->hasPrimaryKey()) {
return '';
}
$this->declareClasses('\Propel\Runtime\Connection\ConnectionInterface');
$script .= "
/**
* Find object by primary key.
*
* @param mixed \$key Primary key to use for the query
* @param ConnectionInterface \$con A connection object
*
* @return " . $class . "|array|mixed the result, formatted by the current formatter
*/
protected function findPkComplex(\$key, ConnectionInterface \$con)
{
// As the query uses a PK condition, no limit(1) is necessary.
\$criteria = \$this->isKeepQuery() ? clone \$this : \$this;
\$dataFetcher = \$criteria
->filterByPrimaryKey(\$key)
->doSelect(\$con);
return \$criteria->getFormatter()->init(\$criteria)->formatOne(\$dataFetcher);
}
";
}
/**
* Adds the findPks method for this object.
* @param string &$script The script will be modified in this method.
*/
protected function addFindPks(&$script)
{
$this->declareClasses(
'\Propel\Runtime\Collection\ObjectCollection',
'\Propel\Runtime\Connection\ConnectionInterface',
'\Propel\Runtime\Propel'
);
$table = $this->getTable();
$pks = $table->getPrimaryKey();
$count = count($pks);
$script .= "
/**
* Find objects by primary key
* <code>";
if (1 === $count) {
$script .= "
* \$objs = \$c->findPks(array(12, 56, 832), \$con);";
} else {
$script .= "
* \$objs = \$c->findPks(array(array(12, 56), array(832, 123), array(123, 456)), \$con);";
}
$script .= "
* </code>
* @param array \$keys Primary keys to use for the query
* @param ConnectionInterface \$con an optional connection object
*
* @return ObjectCollection|array|mixed the list of results, formatted by the current formatter
*/
public function findPks(\$keys, ConnectionInterface \$con = null)
{";
if (!$table->hasPrimaryKey()) {
$this->declareClass('Propel\\Runtime\\Exception\\LogicException');
$script .= "
throw new LogicException('The {$this->getObjectName()} object has no primary key');
}
";
return $script;
}
$script .= "
if (null === \$con) {
\$con = Propel::getServiceContainer()->getReadConnection(\$this->getDbName());
}
\$this->basePreSelect(\$con);
\$criteria = \$this->isKeepQuery() ? clone \$this : \$this;
\$dataFetcher = \$criteria
->filterByPrimaryKeys(\$keys)
->doSelect(\$con);
return \$criteria->getFormatter()->init(\$criteria)->format(\$dataFetcher);
}
";
}
/**
* Adds the filterByPrimaryKey method for this object.
* @param string &$script The script will be modified in this method.
*/
protected function addFilterByPrimaryKey(&$script)
{
$script .= "
/**
* Filter the query by primary key
*
* @param mixed \$key Primary key to use for the query
*
* @return \$this|" . $this->getQueryClassName() . " The current query, for fluid interface
*/
public function filterByPrimaryKey(\$key)
{";
$table = $this->getTable();
if (!$table->hasPrimaryKey()) {
$this->declareClass('Propel\\Runtime\\Exception\\LogicException');
$script .= "
throw new LogicException('The {$this->getObjectName()} object has no primary key');
}
";
return $script;
}
$pks = $table->getPrimaryKey();
if (1 === count($pks)) {
// simple primary key
$col = $pks[0];
$const = $this->getColumnConstant($col);
$script .= "
return \$this->addUsingAlias($const, \$key, Criteria::EQUAL);";
} else {
// composite primary key
$i = 0;
foreach ($pks as $col) {
$const = $this->getColumnConstant($col);
$script .= "
\$this->addUsingAlias($const, \$key[$i], Criteria::EQUAL);";
$i++;
}
$script .= "
return \$this;";
}
$script .= "
}
";
}
/**
* Adds the filterByPrimaryKey method for this object.
* @param string &$script The script will be modified in this method.
*/
protected function addFilterByPrimaryKeys(&$script)
{
$script .= "
/**
* Filter the query by a list of primary keys
*
* @param array \$keys The list of primary key to use for the query
*
* @return \$this|" . $this->getQueryClassName() . " The current query, for fluid interface
*/
public function filterByPrimaryKeys(\$keys)
{";
$table = $this->getTable();
if (!$table->hasPrimaryKey()) {
$this->declareClass('Propel\\Runtime\\Exception\\LogicException');
$script .= "
throw new LogicException('The {$this->getObjectName()} object has no primary key');
}
";
return $script;
}
$pks = $table->getPrimaryKey();
if (1 === count($pks)) {
// simple primary key
$col = $pks[0];
$const = $this->getColumnConstant($col);
$script .= "
return \$this->addUsingAlias($const, \$keys, Criteria::IN);";
} else {
// composite primary key
$script .= "
if (empty(\$keys)) {
return \$this->add(null, '1<>1', Criteria::CUSTOM);
}
foreach (\$keys as \$key) {";
$i = 0;
foreach ($pks as $col) {
$const = $this->getColumnConstant($col);
$script .= "
\$cton$i = \$this->getNewCriterion($const, \$key[$i], Criteria::EQUAL);";
if ($i > 0) {
$script .= "
\$cton0->addAnd(\$cton$i);";
}
$i++;
}
$script .= "
\$this->addOr(\$cton0);
}";
$script .= "
return \$this;";
}
$script .= "
}
";
}
/**
* Adds the filterByCol method for this object.
* @param string &$script The script will be modified in this method.
* @param Column $col
*/
protected function addFilterByCol(&$script, Column $col)
{
$colPhpName = $col->getPhpName();
$colName = $col->getName();
$variableName = $col->getCamelCaseName();
$qualifiedName = $this->getColumnConstant($col);
$script .= "
/**
* Filter the query on the $colName column
*";
if ($col->isNumericType()) {
$script .= "
* Example usage:
* <code>
* \$query->filterBy$colPhpName(1234); // WHERE $colName = 1234
* \$query->filterBy$colPhpName(array(12, 34)); // WHERE $colName IN (12, 34)
* \$query->filterBy$colPhpName(array('min' => 12)); // WHERE $colName > 12
* </code>";
if ($col->isForeignKey()) {
foreach ($col->getForeignKeys() as $fk) {
$script .= "
*
* @see filterBy" . $this->getFKPhpNameAffix($fk) . "()";
}
}
$script .= "
*
* @param mixed \$$variableName The value to use as filter.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => \$minValue, 'max' => \$maxValue) for intervals.";
} elseif ($col->isTemporalType()) {
$script .= "
* Example usage:
* <code>
* \$query->filterBy$colPhpName('2011-03-14'); // WHERE $colName = '2011-03-14'
* \$query->filterBy$colPhpName('now'); // WHERE $colName = '2011-03-14'
* \$query->filterBy$colPhpName(array('max' => 'yesterday')); // WHERE $colName > '2011-03-13'
* </code>
*
* @param mixed \$$variableName The value to use as filter.
* Values can be integers (unix timestamps), DateTime objects, or strings.
* Empty strings are treated as NULL.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => \$minValue, 'max' => \$maxValue) for intervals.";
} elseif ($col->getType() == PropelTypes::PHP_ARRAY) {
$script .= "
* @param array \$$variableName The values to use as filter.";
} elseif ($col->isTextType()) {
$script .= "
* Example usage:
* <code>
* \$query->filterBy$colPhpName('fooValue'); // WHERE $colName = 'fooValue'
* \$query->filterBy$colPhpName('%fooValue%', Criteria::LIKE); // WHERE $colName LIKE '%fooValue%'
* </code>
*
* @param string \$$variableName The value to use as filter.";
} elseif ($col->isBooleanType()) {
$script .= "
* Example usage:
* <code>
* \$query->filterBy$colPhpName(true); // WHERE $colName = true
* \$query->filterBy$colPhpName('yes'); // WHERE $colName = true
* </code>
*
* @param boolean|string \$$variableName The value to use as filter.
* Non-boolean arguments are converted using the following rules:
* * 1, '1', 'true', 'on', and 'yes' are converted to boolean true
* * 0, '0', 'false', 'off', and 'no' are converted to boolean false
* Check on string values is case insensitive (so 'FaLsE' is seen as 'false').";
} else {
$script .= "
* @param mixed \$$variableName The value to use as filter";
}
$script .= "
* @param string \$comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*