This repository has been archived by the owner on Nov 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 219
/
Table.php
2858 lines (2544 loc) · 93.9 KB
/
Table.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
/*
* $Id: Table.php 7681 2010-08-24 15:55:34Z jwage $
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
/**
* Doctrine_Table represents a database table
* each Doctrine_Table holds the information of foreignKeys and associations
*
*
* @author Konsta Vesterinen <kvesteri@cc.hut.fi>
* @package Doctrine
* @subpackage Table
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @version $Revision: 7681 $
* @link www.doctrine-project.org
* @since 1.0
* @method mixed findBy*(mixed $value) magic finders; @see __call()
* @method mixed findOneBy*(mixed $value) magic finders; @see __call()
*/
class Doctrine_Table extends Doctrine_Configurable implements Countable
{
/**
* @var array $data temporary data which is then loaded into Doctrine_Record::$_data
*/
protected $_data = array();
/**
* @var mixed $identifier The field names of all fields that are part of the identifier/primary key
*/
protected $_identifier = array();
/**
* @see Doctrine_Identifier constants
* @var integer $identifierType the type of identifier this table uses
*/
protected $_identifierType;
/**
* @var Doctrine_Connection $conn Doctrine_Connection object that created this table
*/
protected $_conn;
/**
* @var array $identityMap first level cache
*/
protected $_identityMap = array();
/**
* @var Doctrine_Table_Repository $repository record repository
*/
protected $_repository;
/**
* @var array $columns an array of column definitions,
* keys are column names and values are column definitions
*
* the definition array has atleast the following values:
*
* -- type the column type, eg. 'integer'
* -- length the column length, eg. 11
*
* additional keys:
* -- notnull whether or not the column is marked as notnull
* -- values enum values
* -- notblank notblank validator + notnull constraint
* ... many more
*/
protected $_columns = array();
/**
* Array of unique sets of fields. These values are validated on save
*
* @var array $_uniques
*/
protected $_uniques = array();
/**
* @var array $_fieldNames an array of field names, used to look up field names
* from column names. Keys are column
* names and values are field names.
* Alias for columns are here.
*/
protected $_fieldNames = array();
/**
*
* @var array $_columnNames an array of column names
* keys are field names and values column names.
* used to look up column names from field names.
* this is the reverse lookup map of $_fieldNames.
*/
protected $_columnNames = array();
/**
* @var integer $columnCount cached column count, Doctrine_Record uses this column count in when
* determining its state
*/
protected $columnCount;
/**
* @var boolean $hasDefaultValues whether or not this table has default values
*/
protected $hasDefaultValues;
/**
* @var array $options an array containing all options
*
* -- name name of the component, for example component name of the GroupTable is 'Group'
*
* -- parents the parent classes of this component
*
* -- declaringClass name of the table definition declaring class (when using inheritance the class
* that defines the table structure can be any class in the inheritance hierarchy,
* hence we need reflection to check out which class actually calls setTableDefinition)
*
* -- tableName database table name, in most cases this is the same as component name but in some cases
* where one-table-multi-class inheritance is used this will be the name of the inherited table
*
* -- sequenceName Some databases need sequences instead of auto incrementation primary keys,
* you can set specific sequence for your table by calling setOption('sequenceName', $seqName)
* where $seqName is the name of the desired sequence
*
* -- enumMap enum value arrays
*
* -- inheritanceMap inheritanceMap is used for inheritance mapping, keys representing columns and values
* the column values that should correspond to child classes
*
* -- type table type (mysql example: INNODB)
*
* -- charset character set
*
* -- foreignKeys the foreign keys of this table
*
* -- checks the check constraints of this table, eg. 'price > dicounted_price'
*
* -- collate collate attribute
*
* -- indexes the index definitions of this table
*
* -- treeImpl the tree implementation of this table (if any)
*
* -- treeOptions the tree options
*
* -- queryParts the bound query parts
*
* -- versioning
*/
protected $_options = array('name' => null,
'tableName' => null,
'sequenceName' => null,
'inheritanceMap' => array(),
'enumMap' => array(),
'type' => null,
'charset' => null,
'collate' => null,
'treeImpl' => null,
'treeOptions' => array(),
'indexes' => array(),
'parents' => array(),
'joinedParents' => array(),
'queryParts' => array(),
'versioning' => null,
'subclasses' => array(),
'orderBy' => null
);
/**
* @var Doctrine_Tree $tree tree object associated with this table
*/
protected $_tree;
/**
* @var Doctrine_Relation_Parser $_parser relation parser object
*/
protected $_parser;
/**
* @see Doctrine_Template
* @var array $_templates an array containing all templates attached to this table
*/
protected $_templates = array();
/**
* @see Doctrine_Record_Filter
* @var array $_filters an array containing all record filters attached to this table
*/
protected $_filters = array();
/**
* @see Doctrine_Record_Generator
* @var array $_generators an array containing all generators attached to this table
*/
protected $_generators = array();
/**
* Generator instance responsible for constructing this table
*
* @see Doctrine_Record_Generator
* @var Doctrine_Record_Generator $generator
*/
protected $_generator;
/**
* @var array $_invokedMethods method invoker cache
*/
protected $_invokedMethods = array();
/**
* @var Doctrine_Record $record empty instance of the given model
*/
protected $record;
/**
* the constructor
*
* @throws Doctrine_Connection_Exception if there are no opened connections
* @param string $name the name of the component
* @param Doctrine_Connection $conn the connection associated with this table
* @param boolean $initDefinition whether to init the in-memory schema
*/
public function __construct($name, Doctrine_Connection $conn, $initDefinition = false)
{
$this->_conn = $conn;
$this->_options['name'] = $name;
$this->setParent($this->_conn);
$this->_conn->addTable($this);
$this->_parser = new Doctrine_Relation_Parser($this);
if ($charset = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_TABLE_CHARSET)) {
$this->_options['charset'] = $charset;
}
if ($collate = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_TABLE_COLLATE)) {
$this->_options['collate'] = $collate;
}
if ($initDefinition) {
$this->record = $this->initDefinition();
$this->initIdentifier();
$this->record->setUp();
// if tree, set up tree
if ($this->isTree()) {
$this->getTree()->setUp();
}
} else {
if ( ! isset($this->_options['tableName'])) {
$this->setTableName(Doctrine_Inflector::tableize($this->_options['name']));
}
}
$this->_filters[] = new Doctrine_Record_Filter_Standard();
$this->_repository = new Doctrine_Table_Repository($this);
$this->construct();
}
/**
* Construct template method.
*
* This method provides concrete Table classes with the possibility
* to hook into the constructor procedure. It is called after the
* Doctrine_Table construction process is finished.
*
* @return void
*/
public function construct()
{ }
/**
* Initializes the in-memory table definition.
*
* @param string $name
*/
public function initDefinition()
{
$name = $this->_options['name'];
if ( ! class_exists($name) || empty($name)) {
throw new Doctrine_Exception("Couldn't find class " . $name);
}
$record = new $name($this);
$names = array();
$class = $name;
// get parent classes
do {
if ($class === 'Doctrine_Record') {
break;
}
$name = $class;
$names[] = $name;
} while ($class = get_parent_class($class));
if ($class === false) {
throw new Doctrine_Table_Exception('Class "' . $name . '" must be a child class of Doctrine_Record');
}
// reverse names
$names = array_reverse($names);
// save parents
array_pop($names);
$this->_options['parents'] = $names;
// create database table
if (method_exists($record, 'setTableDefinition')) {
$record->setTableDefinition();
// get the declaring class of setTableDefinition method
$method = new ReflectionMethod($this->_options['name'], 'setTableDefinition');
$class = $method->getDeclaringClass();
} else {
$class = new ReflectionClass($class);
}
$this->_options['joinedParents'] = array();
foreach (array_reverse($this->_options['parents']) as $parent) {
if ($parent === $class->getName()) {
continue;
}
$ref = new ReflectionClass($parent);
if ($ref->isAbstract() || ! $class->isSubClassOf($parent)) {
continue;
}
$parentTable = $this->_conn->getTable($parent);
$found = false;
$parentColumns = $parentTable->getColumns();
foreach ($parentColumns as $columnName => $definition) {
if ( ! isset($definition['primary']) || $definition['primary'] === false) {
if (isset($this->_columns[$columnName])) {
$found = true;
break;
} else {
if ( ! isset($parentColumns[$columnName]['owner'])) {
$parentColumns[$columnName]['owner'] = $parentTable->getComponentName();
}
$this->_options['joinedParents'][] = $parentColumns[$columnName]['owner'];
}
} else {
unset($parentColumns[$columnName]);
}
}
if ($found) {
continue;
}
foreach ($parentColumns as $columnName => $definition) {
$fullName = $columnName . ' as ' . $parentTable->getFieldName($columnName);
$this->setColumn($fullName, $definition['type'], $definition['length'], $definition, true);
}
break;
}
$this->_options['joinedParents'] = array_values(array_unique($this->_options['joinedParents']));
$this->_options['declaringClass'] = $class;
// set the table definition for the given tree implementation
if ($this->isTree()) {
$this->getTree()->setTableDefinition();
}
$this->columnCount = count($this->_columns);
if ( ! isset($this->_options['tableName'])) {
$this->setTableName(Doctrine_Inflector::tableize($class->getName()));
}
return $record;
}
/**
* Initializes the primary key.
*
* Called in the construction process, builds the identifier definition
* copying in the schema the list of the fields which constitutes
* the primary key.
*
* @return void
*/
public function initIdentifier()
{
switch (count($this->_identifier)) {
case 0:
if ( ! empty($this->_options['joinedParents'])) {
$root = current($this->_options['joinedParents']);
$table = $this->_conn->getTable($root);
$this->_identifier = $table->getIdentifier();
$this->_identifierType = ($table->getIdentifierType() !== Doctrine_Core::IDENTIFIER_AUTOINC)
? $table->getIdentifierType() : Doctrine_Core::IDENTIFIER_NATURAL;
// add all inherited primary keys
foreach ((array) $this->_identifier as $id) {
$definition = $table->getDefinitionOf($id);
// inherited primary keys shouldn't contain autoinc
// and sequence definitions
unset($definition['autoincrement']);
unset($definition['sequence']);
// add the inherited primary key column
$fullName = $id . ' as ' . $table->getFieldName($id);
$this->setColumn($fullName, $definition['type'], $definition['length'],
$definition, true);
}
} else {
$identifierOptions = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_IDENTIFIER_OPTIONS);
$name = (isset($identifierOptions['name']) && $identifierOptions['name']) ? $identifierOptions['name']:'id';
$name = sprintf($name, $this->getTableName());
$definition = array('type' => (isset($identifierOptions['type']) && $identifierOptions['type']) ? $identifierOptions['type']:'integer',
'length' => (isset($identifierOptions['length']) && $identifierOptions['length']) ? $identifierOptions['length']:8,
'autoincrement' => isset($identifierOptions['autoincrement']) ? $identifierOptions['autoincrement']:true,
'primary' => isset($identifierOptions['primary']) ? $identifierOptions['primary']:true);
unset($identifierOptions['name'], $identifierOptions['type'], $identifierOptions['length']);
foreach ($identifierOptions as $key => $value) {
if ( ! isset($definition[$key]) || ! $definition[$key]) {
$definition[$key] = $value;
}
}
$this->setColumn($name, $definition['type'], $definition['length'], $definition, true);
$this->_identifier = $name;
$this->_identifierType = Doctrine_Core::IDENTIFIER_AUTOINC;
}
$this->columnCount++;
break;
case 1:
foreach ($this->_identifier as $pk) {
$e = $this->getDefinitionOf($pk);
$found = false;
foreach ($e as $option => $value) {
if ($found) {
break;
}
$e2 = explode(':', $option);
switch (strtolower($e2[0])) {
case 'autoincrement':
case 'autoinc':
if ($value !== false) {
$this->_identifierType = Doctrine_Core::IDENTIFIER_AUTOINC;
$found = true;
}
break;
case 'seq':
case 'sequence':
$this->_identifierType = Doctrine_Core::IDENTIFIER_SEQUENCE;
$found = true;
if (is_string($value)) {
$this->_options['sequenceName'] = $value;
} else {
if (($sequence = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_SEQUENCE)) !== null) {
$this->_options['sequenceName'] = $sequence;
} else {
$this->_options['sequenceName'] = $this->_conn->formatter->getSequenceName($this->_options['tableName']);
}
}
break;
}
}
if ( ! isset($this->_identifierType)) {
$this->_identifierType = Doctrine_Core::IDENTIFIER_NATURAL;
}
}
$this->_identifier = $pk;
break;
default:
$this->_identifierType = Doctrine_Core::IDENTIFIER_COMPOSITE;
}
}
/**
* Gets the owner of a column.
*
* The owner of a column is the name of the component in a hierarchy that
* defines the column.
*
* @param string $columnName the column name
* @return string the name of the owning/defining component
*/
public function getColumnOwner($columnName)
{
if (isset($this->_columns[$columnName]['owner'])) {
return $this->_columns[$columnName]['owner'];
} else {
return $this->getComponentName();
}
}
/**
* Gets the record instance for this table.
*
* The Doctrine_Table instance always holds at least one
* instance of a model so that it can be reused for several things,
* but primarily it is first used to instantiate all the internal
* in memory schema definition.
*
* @return Doctrine_Record Empty instance of the record
*/
public function getRecordInstance()
{
if ( ! $this->record) {
$this->record = new $this->_options['name'];
}
return $this->record;
}
/**
* Checks whether a column is inherited from a component further up in the hierarchy.
*
* @param $columnName The column name
* @return boolean TRUE if column is inherited, FALSE otherwise.
*/
public function isInheritedColumn($columnName)
{
return (isset($this->_columns[$columnName]['owner']));
}
/**
* Checks whether a field is in the primary key.
*
* Checks if $fieldName is part of the table identifier, which defines
* the one-column or multi-column primary key.
*
* @param string $fieldName The field name
* @return boolean TRUE if the field is part of the table identifier/primary key field(s),
*/
public function isIdentifier($fieldName)
{
return ($fieldName === $this->getIdentifier() ||
in_array($fieldName, (array) $this->getIdentifier()));
}
/**
* Checks whether a field identifier is of type autoincrement.
*
* This method checks if the primary key is a AUTOINCREMENT column or
* if the table uses a natural key.
*
* @return boolean TRUE if the identifier is autoincrement
* FALSE otherwise
*/
public function isIdentifierAutoincrement()
{
return $this->getIdentifierType() === Doctrine_Core::IDENTIFIER_AUTOINC;
}
/**
* Checks whether a field identifier is a composite key.
*
* @return boolean TRUE if the identifier is a composite key,
* FALSE otherwise
*/
public function isIdentifierComposite()
{
return $this->getIdentifierType() === Doctrine_Core::IDENTIFIER_COMPOSITE;
}
/**
* getMethodOwner
*
* @param string $method
* @return void
*/
public function getMethodOwner($method)
{
return (isset($this->_invokedMethods[$method])) ?
$this->_invokedMethods[$method] : false;
}
/**
* setMethodOwner
*
* @param string $method
* @param string $class
*/
public function setMethodOwner($method, $class)
{
$this->_invokedMethods[$method] = $class;
}
/**
* Exports this table to database based on the schema definition.
*
* This method create a physical table in the database, using the
* definition that comes from the component Doctrine_Record instance.
*
* @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS
* occurred during the create table operation
* @return boolean whether or not the export operation was successful
* false if table already existed in the database
*/
public function export()
{
$this->_conn->export->exportTable($this);
}
/**
* Returns an exportable representation of this object.
*
* This method produces a array representation of the table schema, where
* keys are tableName, columns (@see $_columns) and options.
* The options subarray contains 'primary' and 'foreignKeys'.
*
* @param boolean $parseForeignKeys whether to include foreign keys definition in the options
* @return array
*/
public function getExportableFormat($parseForeignKeys = true)
{
$columns = array();
$primary = array();
foreach ($this->getColumns() as $name => $definition) {
if (isset($definition['owner'])) {
continue;
}
switch ($definition['type']) {
case 'boolean':
if (isset($definition['default'])) {
$definition['default'] = $this->getConnection()->convertBooleans($definition['default']);
}
break;
}
$columns[$name] = $definition;
if (isset($definition['primary']) && $definition['primary']) {
$primary[] = $name;
}
}
$options['foreignKeys'] = isset($this->_options['foreignKeys']) ?
$this->_options['foreignKeys'] : array();
if ($parseForeignKeys && $this->getAttribute(Doctrine_Core::ATTR_EXPORT) & Doctrine_Core::EXPORT_CONSTRAINTS) {
$constraints = array();
$emptyIntegrity = array('onUpdate' => null,
'onDelete' => null);
foreach ($this->getRelations() as $name => $relation) {
$fk = $relation->toArray();
$fk['foreignTable'] = $relation->getTable()->getTableName();
// do not touch tables that have EXPORT_NONE attribute
if ($relation->getTable()->getAttribute(Doctrine_Core::ATTR_EXPORT) === Doctrine_Core::EXPORT_NONE) {
continue;
}
if ($relation->getTable() === $this && in_array($relation->getLocal(), $primary)) {
if ($relation->hasConstraint()) {
throw new Doctrine_Table_Exception("Badly constructed integrity constraints. Cannot define constraint of different fields in the same table.");
}
continue;
}
$integrity = array('onUpdate' => $fk['onUpdate'],
'onDelete' => $fk['onDelete']);
$fkName = $relation->getForeignKeyName();
if ($relation instanceof Doctrine_Relation_LocalKey) {
$def = array('name' => $fkName,
'local' => $relation->getLocalColumnName(),
'foreign' => $relation->getForeignColumnName(),
'foreignTable' => $relation->getTable()->getTableName());
if ($integrity !== $emptyIntegrity) {
$def = array_merge($def, $integrity);
}
if (($key = $this->_checkForeignKeyExists($def, $options['foreignKeys'])) === false) {
$options['foreignKeys'][$fkName] = $def;
} else {
unset($def['name']);
$options['foreignKeys'][$key] = array_merge($options['foreignKeys'][$key], $def);
}
}
}
}
$options['primary'] = $primary;
return array('tableName' => $this->getOption('tableName'),
'columns' => $columns,
'options' => array_merge($this->getOptions(), $options));
}
/**
* Check if a foreign definition already exists in the fks array for a
* foreign table, local and foreign key
*
* @param array $def Foreign key definition to check for
* @param array $foreignKeys Array of existing foreign key definitions to check in
* @return boolean $result Whether or not the foreign key was found
*/
protected function _checkForeignKeyExists($def, $foreignKeys)
{
foreach ($foreignKeys as $key => $foreignKey) {
if ($def['local'] == $foreignKey['local'] && $def['foreign'] == $foreignKey['foreign'] && $def['foreignTable'] == $foreignKey['foreignTable']) {
return $key;
}
}
return false;
}
/**
* Retrieves the relation parser associated with this table.
*
* @return Doctrine_Relation_Parser relation parser object
*/
public function getRelationParser()
{
return $this->_parser;
}
/**
* Magic method for accessing to object properties.
*
* This method is an alias for getOption.
* <code>
* foreach ($table->indexes as $name => $definition) {
* // ...
* }
* </code>
*
* @param string $option
* @return mixed
*/
public function __get($option)
{
if (isset($this->_options[$option])) {
return $this->_options[$option];
}
return null;
}
/**
* Magic method for testing object properties existence.
*
* This method tests if an option exists.
* <code>
* if (isset($table->tableName)) {
* // ...
* }
* </code>
*
* @param string $option
*/
public function __isset($option)
{
return isset($this->_options[$option]);
}
/**
* Retrieves all options of this table and the associated values.
*
* @return array all options and their values
*/
public function getOptions()
{
return $this->_options;
}
/**
* Sets all the options.
*
* This method sets options of the table that are specified in the argument.
* It has no effect on other options.
*
* @param array $options keys are option names
* @return void
*/
public function setOptions($options)
{
foreach ($options as $key => $value) {
$this->setOption($key, $value);
}
}
/**
* Adds a foreignKey to the table in-memory definition.
*
* This method adds a foreign key to the schema definition.
* It does not add the key to the physical table in the db; @see export().
*
* @param array $definition definition of the foreign key
* @return void
*/
public function addForeignKey(array $definition)
{
$this->_options['foreignKeys'][] = $definition;
}
/**
* Adds a check constraint to the table in-memory definition.
*
* This method adds a CHECK constraint to the schema definition.
* It does not add the constraint to the physical table in the
* db; @see export().
*
* @param $definition
* @param mixed $name if string used as name for the constraint.
* Otherwise it is indexed numerically.
* @return void
*/
public function addCheckConstraint($definition, $name)
{
if (is_string($name)) {
$this->_options['checks'][$name] = $definition;
} else {
$this->_options['checks'][] = $definition;
}
return $this;
}
/**
* Adds an index to this table in-memory definition.
*
* This method adds an INDEX to the schema definition.
* It does not add the index to the physical table in the db; @see export().
*
* @param string $index index name
* @param array $definition keys are type, fields
* @return void
*/
public function addIndex($index, array $definition)
{
if (isset($definition['fields'])) {
foreach ((array) $definition['fields'] as $key => $field) {
if (is_numeric($key)) {
$definition['fields'][$key] = $this->getColumnName($field);
} else {
$columnName = $this->getColumnName($key);
unset($definition['fields'][$key]);
$definition['fields'][$columnName] = $field;
}
}
}
$this->_options['indexes'][$index] = $definition;
}
/**
* Retrieves an index definition.
*
* This method returns a given index definition: @see addIndex().
*
* @param string $index index name; @see addIndex()
* @return array|boolean array on success, FALSE on failure
*/
public function getIndex($index)
{
if (isset($this->_options['indexes'][$index])) {
return $this->_options['indexes'][$index];
}
return false;
}
/**
* Defines a n-uple of fields that must be unique for every record.
*
* This method Will automatically add UNIQUE index definition
* and validate the values on save. The UNIQUE index is not created in the
* database until you use @see export().
*
* @param array $fields values are fieldnames
* @param array $options array of options for unique validator
* @param bool $createUniqueIndex Whether or not to create a unique index in the database
* @return void
*/
public function unique($fields, $options = array(), $createdUniqueIndex = true)
{
if ($createdUniqueIndex) {
$name = implode('_', $fields) . '_unqidx';
$definition = array('type' => 'unique', 'fields' => $fields);
$this->addIndex($name, $definition);
}
$this->_uniques[] = array($fields, $options);
}
/**
* Adds a relation to the table.
*
* This method defines a relation on this table, that will be present on
* every record belonging to this component.
*
* @param array $args first value is a string, name of related component;
* second value is array, options for the relation.
* @see Doctrine_Relation::_$definition
* @param integer $type Doctrine_Relation::ONE or Doctrine_Relation::MANY
* @return void
* @todo Name proposal: addRelation
*/
public function bind($args, $type)
{
$options = ( ! isset($args[1])) ? array() : $args[1];
$options['type'] = $type;
$this->_parser->bind($args[0], $options);
}
/**
* Binds One-to-One aggregate relation
*
* @param string $componentName the name of the related component
* @param string $options relation options
* @see Doctrine_Relation::_$definition
* @return Doctrine_Record this object
*/
public function hasOne()
{
$this->bind(func_get_args(), Doctrine_Relation::ONE);
}
/**
* Binds One-to-Many / Many-to-Many aggregate relation
*
* @param string $componentName the name of the related component
* @param string $options relation options
* @see Doctrine_Relation::_$definition
* @return Doctrine_Record this object
*/
public function hasMany()
{
$this->bind(func_get_args(), Doctrine_Relation::MANY);
}
/**
* Tests if a relation exists.
*
* This method queries the table definition to find out if a relation
* is defined for this component. Alias defined with foreignAlias are not
* recognized as there's only one Doctrine_Relation object on the owning
* side.
*
* @param string $alias the relation alias to search for.
* @return boolean true if the relation exists. Otherwise false.
*/
public function hasRelation($alias)
{
return $this->_parser->hasRelation($alias);
}
/**
* Retrieves a relation object for this component.
*
* @param string $alias relation alias; @see hasRelation()
* @return Doctrine_Relation
*/
public function getRelation($alias, $recursive = true)
{