-
Notifications
You must be signed in to change notification settings - Fork 95
/
sfPropelGenerator.class.php
598 lines (544 loc) · 18.4 KB
/
sfPropelGenerator.class.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
<?php
/*
* This file is part of the symfony package.
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Propel generator.
*
* @package symfony
* @subpackage propel
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @version SVN: $Id: sfPropelGenerator.class.php 22943 2009-10-12 12:04:19Z Kris.Wallsmith $
*/
class sfPropelGenerator extends sfModelGenerator
{
protected
$tableMap = null,
$dbMap = null;
/**
* Initializes the current sfGenerator instance.
*
* @param sfGeneratorManager $generatorManager A sfGeneratorManager instance
*/
public function initialize(sfGeneratorManager $generatorManager)
{
parent::initialize($generatorManager);
$this->setGeneratorClass('sfPropelModule');
}
/**
* Configures this generator.
*/
public function configure()
{
// get some model metadata
$this->loadMapBuilderClasses();
// load all primary keys
$this->loadPrimaryKeys();
}
/**
* Gets the table map for the current model class.
*
* @return TableMap A TableMap instance
*/
public function getTableMap()
{
return $this->tableMap;
}
/**
* Returns an array of tables that represents a many to many relationship.
*
* A table is considered to be a m2m table if it has 2 foreign keys that are also primary keys.
*
* @return array An array of tables.
*/
public function getManyToManyTables()
{
$tables = array();
$middleTables = array();
$foreignTables = array();
$relations = array();
// go through all relations
$table = $this->getTableMap();
foreach ($table->getRelations() as $relation)
{
//we have a many to many Relation
if (RelationMap::MANY_TO_MANY === $relation->getType())
{
$foreignTables[$relation->getLocalTable()->getClassname()] = $relation;
}
else if (RelationMap::ONE_TO_MANY === $relation->getType())
{
$relations[$relation->getLocalTable()->getClassname()] = $relation;
}
}
// find middleTable for Many to Many relation
foreach ($foreignTables as $tableName => $relation)
{
$foreignTable = $relation->getLocalTable();
foreach ($foreignTable->getRelations() as $foreignRelation)
{
$foreignTableClassname = $foreignRelation->getLocalTable()->getClassname();
// Test if the foreign table has a common relation with our table
if (RelationMap::ONE_TO_MANY === $foreignRelation->getType()
&& array_key_exists($foreignTableClassname, $relations))
{
$columns = $relations[$foreignTableClassname]->getLocalColumns();
$relatedColumns = $foreignRelation->getLocalColumns();
$middleTable = $foreignRelation->getLocalTable();
if ($middleTable->isCrossRef() && !isset($middleTables[$middleTable->getClassname()]))
{
// Add this middleTable to table list to prevent using it twice
$middleTables[$middleTable->getClassname()] = $middleTable;
$tables[] = array(
'middleTable' => $middleTable,
'relatedTable' => $foreignTable,
'column' => reset($columns),
'relatedColumn' => reset($relatedColumns),
);
continue 2;
}
}
}
}
//Keep BC with M2M without isCrossRef = true
foreach ($relations as $relation)
{
$middleTable = $relation->getLocalTable();
//check if $middleTable is a Many 2 Many :
// exclude already found middle table
// if there it has 2 PKs
// if there id only 2 columns in the table
// if PKs are also FKs
if (!isset($middleTables[$middleTable->getClassname()])
&& 2 === count($pks = $middleTable->getPrimaryKeyColumns())
&& 2 === count($middleTable->getColumns())
&& $pks[0]->isForeignKey()
&& $pks[1]->isForeignKey())
{
//We found a Many to Many middle table
$foreignTable = $pks[0]->getRelatedTableName() != $table->getName() ? $pks[0]->getRelatedTable() : $pks[1]->getRelatedTable();
$relatedColumn = $pks[0]->getRelatedTableName() != $table->getName() ? $pks[0] : $pks[1];
$columns = $relation->getLocalColumns();
// Add this middleTable to table list to prevent using it twice
$middleTables[$middleTable->getClassname()] = $middleTable;
$tables[] = array(
'middleTable' => $middleTable,
'relatedTable' => $foreignTable,
'column' => reset($columns),
'relatedColumn' => $relatedColumn,
);
}
}
return $tables;
}
/**
* Loads primary keys.
*
* @throws sfException
*/
protected function loadPrimaryKeys()
{
$this->primaryKey = array();
foreach ($this->tableMap->getPrimaryKeys() as $column)
{
$this->primaryKey[] = $column->getPhpName();
}
if (!count($this->primaryKey))
{
throw new sfException(sprintf('Cannot generate a module for a model without a primary key (%s)', $this->modelClass));
}
}
/**
* Loads map builder classes.
*
* @throws sfException
*/
protected function loadMapBuilderClasses()
{
$this->dbMap = Propel::getDatabaseMap();
$this->tableMap = call_user_func(array($this->modelClass . 'Peer', 'getTableMap'));
// load all related table maps,
// and all tables related to the related table maps (for m2m relations)
foreach ($this->tableMap->getRelations() as $relation)
{
foreach ($relation->getForeignTable()->getRelations() as $relationN) {
$relationN->getLocalTable()->getRelations();
}
}
}
/**
* Returns HTML code for a field.
*
* @param sfModelGeneratorConfigurationField $field The field
*
* @return string HTML code
*/
public function renderField($field)
{
if ($field->isLink() && ($module = $field->getConfig('link_module', false, false)))
{
$field->setLink(false);
$html = parent::renderField($field);
$field->setLink(true);
$html = sprintf("link_to(%s, '%s', %s)", $html, $module . '_edit', $html);
return $html;
}
else
{
return parent::renderField($field);
}
}
/**
* Returns the getter either non-developped: 'getFoo' or developped: '$class->getFoo()'.
*
* @param string $column The column name
* @param boolean $developed true if you want developped method names, false otherwise
* @param string $prefix The prefix value
*
* @return string PHP code
*/
public function getColumnGetter($column, $developed = false, $prefix = '')
{
try
{
$getter = 'get'.call_user_func(array(constant($this->getModelClass().'::PEER'), 'translateFieldName'), $column, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_PHPNAME);
}
catch (PropelException $e)
{
// not a real column
$getter = 'get'.sfInflector::camelize($column);
}
if (!$developed)
{
return $getter;
}
return sprintf('$%s%s->%s()', $prefix, $this->getSingularName(), $getter);
}
/**
* Returns the type of a column.
*
* @param object $column A column object
*
* @return string The column type
*/
public function getType($column)
{
if ($column->isForeignKey())
{
return 'ForeignKey';
}
switch ($column->getType())
{
case PropelColumnTypes::BOOLEAN:
case PropelColumnTypes::BOOLEAN_EMU:
return 'Boolean';
case PropelColumnTypes::DATE:
case PropelColumnTypes::TIMESTAMP:
return 'Date';
case PropelColumnTypes::TIME:
return 'Time';
default:
return 'Text';
}
}
/**
* Returns the default configuration for fields.
*
* @return array An array of default configuration for all fields
*/
public function getDefaultFieldsConfiguration()
{
$fields = array();
$names = array();
foreach ($this->getTableMap()->getColumns() as $column)
{
$name = $this->translateColumnName($column);
$names[] = $name;
$fields[$name] = array_merge(array(
'is_link' => (Boolean) $column->isPrimaryKey(),
'is_real' => true,
'is_partial' => false,
'is_component' => false,
'type' => $this->getType($column),
), isset($this->config['fields'][$name]) ? $this->config['fields'][$name] : array());
}
foreach ($this->getManyToManyTables() as $tables)
{
$name = sfInflector::underscore($tables['middleTable']->getClassname()).'_list';
$names[] = $name;
$fields[$name] = array_merge(array(
'is_link' => false,
'is_real' => false,
'is_partial' => false,
'is_component' => false,
'type' => 'Text',
), isset($this->config['fields'][$name]) ? $this->config['fields'][$name] : array());
}
if (isset($this->config['fields']))
{
foreach ($this->config['fields'] as $name => $params)
{
if (in_array($name, $names))
{
continue;
}
$fields[$name] = array_merge(array(
'is_link' => false,
'is_real' => false,
'is_partial' => false,
'is_component' => false,
'type' => 'Text',
), is_array($params) ? $params : array());
}
}
unset($this->config['fields']);
return $fields;
}
/**
* Returns the configuration for fields in a given context.
*
* @param string $context The Context
*
* @return array An array of configuration for all the fields in a given context
*/
public function getFieldsConfiguration($context)
{
$fields = array();
$names = array();
foreach ($this->getTableMap()->getColumns() as $column)
{
$name = $this->translateColumnName($column);
$names[] = $name;
$fields[$name] = isset($this->config[$context]['fields'][$name]) ? $this->config[$context]['fields'][$name] : array();
}
foreach ($this->getManyToManyTables() as $tables)
{
$name = sfInflector::underscore($tables['middleTable']->getClassname()).'_list';
$names[] = $name;
$fields[$name] = isset($this->config[$context]['fields'][$name]) ? $this->config[$context]['fields'][$name] : array();
}
if (isset($this->config[$context]['fields']))
{
foreach ($this->config[$context]['fields'] as $name => $params)
{
if (in_array($name, $names))
{
continue;
}
$fields[$name] = is_array($params) ? $params : array();
}
}
unset($this->config[$context]['fields']);
return $fields;
}
/**
* Gets all the fields for the current model.
*
* @param Boolean $withM2M Whether to include m2m fields or not
*
* @return array An array of field names
*/
public function getAllFieldNames($withM2M = true)
{
$names = array();
foreach ($this->getTableMap()->getColumns() as $column)
{
$names[] = $this->translateColumnName($column);
}
if ($withM2M)
{
foreach ($this->getManyToManyTables() as $tables)
{
$names[] = sfInflector::underscore($tables['middleTable']->getClassname()).'_list';
}
}
return $names;
}
public function translateColumnName($column, $related = false, $to = BasePeer::TYPE_FIELDNAME)
{
$peer = $related ? constant($column->getTable()->getDatabaseMap()->getTable($column->getRelatedTableName())->getPhpName().'::PEER') : constant($column->getTable()->getPhpName().'::PEER');
$field = $related ? $column->getRelatedName() : $column->getFullyQualifiedName();
return call_user_func(array($peer, 'translateFieldName'), $field, BasePeer::TYPE_COLNAME, $to);
}
/**
* Get the code to modify a form object based on fields configuration.
*
* Configuration attributes considered for customization:
* * type
* * widgetClass
* * widgetOptions
* * widgetAttributes (same effect as the 'attributes' attribute)
* * validatorClass
* * validatorOptions
* * validatorMessages
*
* This also removes unused fields from the display list.
*
* <code>
* form:
* display: [foo1, foo2]
* fields:
* foo1: { widgetOptions: { bar: baz } }
* foo2: { widgetClass: sfWidgetFormInputText, validatorClass: sfValidatorPass }
* foo3: { type: plain }
* $form->getWidget('foo1')->setOption('bar', 'baz');
* $form->setWidget('foo2', new sfWidgetFormInputText());
* $form->setValidator('foo2', new sfValidatorPass());
* $form->setWidget('foo3', new sfWidgetFormPlain());
* $form->setValidator('foo3', new sfValidatorPass(array('required' => false)));
* $form->mergePostValidator(new sfValidatorSchemaRemove(array('fields' => array('foo3'))));
* unset($form['foo']);
* </code>
*
* @param string $view Choices are 'edit', 'new', or 'filter'
* @param string $formVariableName The name of the variable referencing the form.
* Choices are 'form', or 'filters'
*
* @return string the form customization code
*/
public function getFormCustomization($view, $formVariableName = 'form')
{
$customization = '';
$form = $this->configuration->getForm(); // fallback field definition
$defaultFieldNames = array_keys($form->getWidgetSchema()->getFields());
$unusedFields = array_combine($defaultFieldNames, $defaultFieldNames);
$fieldsets = ($view == 'filter') ? array('NONE' => $this->configuration->getFormFilterFields($form)) : $this->configuration->getFormFields($form, $view);
$plainFields = array();
foreach ($fieldsets as $fieldset => $fields)
{
foreach ($fields as $fieldName => $field)
{
// plain widget
if ($field->getConfig('type', false) == 'plain')
{
$plainFields[]= $fieldName;
$customization .= " \$this->" . $formVariableName . "->setWidget('$fieldName', new sfWidgetFormPlain());
";
$customization .= " \$this->" . $formVariableName . "->setValidator('$fieldName', new sfValidatorPass(array('required' => false)));
";
}
// widget customization
if (!$widgetConfig = $field->getConfig('widget', array()))
{
if ($widgetClass = $field->getConfig('widgetClass', false))
{
$widgetConfig['class'] = $widgetClass;
}
if ($widgetOptions = $field->getConfig('widgetOptions', false))
{
$widgetConfig['options'] = $widgetOptions;
}
if ($widgetAttributes = $field->getConfig('widgetAttributes', false))
{
$widgetConfig['attributes'] = $widgetAttributes;
}
}
if ($widgetConfig)
{
$options = (isset($widgetConfig['options'])) ? $widgetConfig['options'] : array();
$attributes = (isset($widgetConfig['attributes'])) ? $widgetConfig['attributes'] : array();
if (isset($widgetConfig['class']))
{
$class = $widgetConfig['class'];
$customization .= " \$this->" . $formVariableName . "->setWidget('$fieldName', new $class(" . $this->asPhp($options) . ", " . $this->asPhp($attributes) . "));
";
}
else
{
foreach ($options as $name => $value)
{
$customization .= " \$this->" . $formVariableName . "->getWidget('$fieldName')->setOption('$name', " . $this->asPhp($value) . ");
";
}
foreach ($attributes as $name => $value)
{
$customization .= " \$this->" . $formVariableName . "->getWidget('$fieldName')->setAttribute('$name', " . $this->asPhp($value) . ");
";
}
}
}
// validator configuration
if (!$validatorConfig = $field->getConfig('validator', array()))
{
if ($validatorClass = $field->getConfig('validatorClass', false))
{
$validatorConfig['class'] = $validatorClass;
}
if ($validatorOptions = $field->getConfig('validatorOptions', false))
{
$validatorConfig['options'] = $validatorOptions;
}
if ($validatorMessages = $field->getConfig('validatorMessages', false))
{
$validatorConfig['messages'] = $validatorMessages;
}
}
if ($validatorConfig)
{
$options = (isset($validatorConfig['options'])) ? $validatorConfig['options'] : array();
$messages = (isset($validatorConfig['messages'])) ? $validatorConfig['messages'] : array();
if (isset($validatorConfig['class']))
{
$class = $validatorConfig['class'];
$customization .= " \$this->" . $formVariableName . "->setValidator('$fieldName', new $class(" . $this->asPhp($options) . ", " . $this->asPhp($messages) . "));
";
}
else
{
foreach ($options as $name => $value)
{
$customization .= " \$this->" . $formVariableName . "->getValidator('$fieldName')->setOption('$name', " . $this->asPhp($value) . ");
";
}
foreach ($messages as $name => $value)
{
$customization .= " \$this->" . $formVariableName . "->getValidator('$fieldName')->setMessage('$name', " . $this->asPhp($value) . ");
";
}
}
}
// this field is used
if (isset($unusedFields[$fieldName]))
{
unset($unusedFields[$fieldName]);
}
}
}
// remove plain fields from validation
if (!empty($plainFields))
{
$customization .= " \$this->" . $formVariableName . "->mergePostValidator(new sfValidatorSchemaRemove(array('fields' => " . $this->asPhp($plainFields) . ")));
";
}
// remove unused fields
if (!empty($unusedFields))
{
foreach ($unusedFields as $field)
{
// ignore primary keys, CSRF, and embedded forms
if ($form->getWidget($field) instanceof sfWidgetFormInputHidden
|| $form->getWidget($field) instanceof sfWidgetFormSchemaDecorator)
{
continue;
}
$customization .= " unset(\$this->" . $formVariableName . "['$field']);
";
}
}
return $customization;
}
/**
* check if modelClass has a behavior
* @param string $behavior
* @return boolean
*/
public function hasBehavior($behavior)
{
$behaviors = $this->getTableMap()->getBehaviors();
return isset($behaviors[$behavior]);
}
}