4 * Read the schema specification and parse into internal data structures
6 class CRM_Core_CodeGen_Specification
{
10 protected $classNames;
16 * @param string $buildVersion
17 * Which version of the schema to build.
19 public function parse($schemaPath, $buildVersion, $verbose = TRUE) {
20 $this->buildVersion
= $buildVersion;
23 echo "Parsing schema description " . $schemaPath . "\n";
25 $dbXML = CRM_Core_CodeGen_Util_Xml
::parse($schemaPath);
28 echo "Extracting database information\n";
30 $this->database
= &$this->getDatabase($dbXML);
32 $this->classNames
= array();
34 # TODO: peel DAO-specific stuff out of getTables, and spec reading into its own class
36 echo "Extracting table information\n";
38 $this->tables
= $this->getTables($dbXML, $this->database
);
40 $this->resolveForeignKeys($this->tables
, $this->classNames
);
41 $this->tables
= $this->orderTables($this->tables
);
43 // add archive tables here
44 foreach ($this->tables
as $name => $table) {
45 if ($table['archive'] == 'true') {
46 $name = 'archive_' . $table['name'];
47 $table['name'] = $name;
48 $table['archive'] = 'false';
49 if (isset($table['foreignKey'])) {
50 foreach ($table['foreignKey'] as $fkName => $fkValue) {
51 if ($this->tables
[$fkValue['table']]['archive'] == 'true') {
52 $table['foreignKey'][$fkName]['table'] = 'archive_' . $table['foreignKey'][$fkName]['table'];
53 $table['foreignKey'][$fkName]['uniqName']
54 = str_replace('FK_', 'FK_archive_', $table['foreignKey'][$fkName]['uniqName']);
57 $archiveTables[$name] = $table;
68 public function &getDatabase(&$dbXML) {
69 $database = array('name' => trim((string ) $dbXML->name
));
72 $this->checkAndAppend($attributes, $dbXML, 'character_set', 'DEFAULT CHARACTER SET ', '');
73 $this->checkAndAppend($attributes, $dbXML, 'collate', 'COLLATE ', '');
74 $database['attributes'] = $attributes;
76 $tableAttributes_modern = $tableAttributes_simple = '';
77 $this->checkAndAppend($tableAttributes_modern, $dbXML, 'table_type', 'ENGINE=', '');
78 $this->checkAndAppend($tableAttributes_simple, $dbXML, 'table_type', 'TYPE=', '');
79 $database['tableAttributes_modern'] = trim($tableAttributes_modern . ' ' . $attributes);
80 $database['tableAttributes_simple'] = trim($tableAttributes_simple);
82 $database['comment'] = $this->value('comment', $dbXML, '');
93 public function getTables($dbXML, &$database) {
95 foreach ($dbXML->tables
as $tablesXML) {
96 foreach ($tablesXML->table
as $tableXML) {
97 if ($this->value('drop', $tableXML, 0) > 0 and $this->value('drop', $tableXML, 0) <= $this->buildVersion
) {
101 if ($this->value('add', $tableXML, 0) <= $this->buildVersion
) {
102 $this->getTable($tableXML, $database, $tables);
112 * @param string $classNames
114 public function resolveForeignKeys(&$tables, &$classNames) {
115 foreach (array_keys($tables) as $name) {
116 $this->resolveForeignKey($tables, $classNames, $name);
122 * @param string $classNames
123 * @param string $name
125 public function resolveForeignKey(&$tables, &$classNames, $name) {
126 if (!array_key_exists('foreignKey', $tables[$name])) {
130 foreach (array_keys($tables[$name]['foreignKey']) as $fkey) {
131 $ftable = $tables[$name]['foreignKey'][$fkey]['table'];
132 if (!array_key_exists($ftable, $classNames)) {
133 echo "$ftable is not a valid foreign key table in $name\n";
136 $tables[$name]['foreignKey'][$fkey]['className'] = $classNames[$ftable];
137 $tables[$name]['foreignKey'][$fkey]['fileName'] = str_replace('_', '/', $classNames[$ftable]) . '.php';
138 $tables[$name]['fields'][$fkey]['FKClassName'] = $classNames[$ftable];
147 public function orderTables(&$tables) {
150 while (!empty($tables)) {
151 foreach (array_keys($tables) as $name) {
152 if ($this->validTable($tables, $ordered, $name)) {
153 $ordered[$name] = $tables[$name];
154 unset($tables[$name]);
164 * @param string $name
168 public function validTable(&$tables, &$valid, $name) {
169 if (!array_key_exists('foreignKey', $tables[$name])) {
173 foreach (array_keys($tables[$name]['foreignKey']) as $fkey) {
174 $ftable = $tables[$name]['foreignKey'][$fkey]['table'];
175 if (!array_key_exists($ftable, $valid) && $ftable !== $name) {
187 public function getTable($tableXML, &$database, &$tables) {
188 $name = trim((string ) $tableXML->name
);
189 $klass = trim((string ) $tableXML->class);
190 $base = $this->value('base', $tableXML);
191 $sourceFile = "xml/schema/{$base}/{$klass}.xml";
192 $daoPath = "{$base}/DAO/";
193 $baoPath = __DIR__
. '/../../../' . str_replace(' ', '', "{$base}/BAO/");
194 $pre = str_replace('/', '_', $daoPath);
195 $this->classNames
[$name] = $pre . $klass;
197 $localizable = FALSE;
198 foreach ($tableXML->field
as $fieldXML) {
199 if ($fieldXML->localizable
) {
208 'sourceFile' => $sourceFile,
209 'fileName' => $klass . '.php',
210 'objectName' => $klass,
211 'labelName' => substr($name, 8),
212 'className' => $this->classNames
[$name],
213 'bao' => (file_exists($baoPath . $klass . '.php') ?
str_replace('DAO', 'BAO', $this->classNames
[$name]) : $this->classNames
[$name]),
215 'attributes_simple' => trim($database['tableAttributes_simple']),
216 'attributes_modern' => trim($database['tableAttributes_modern']),
217 'comment' => $this->value('comment', $tableXML),
218 'localizable' => $localizable,
219 'log' => $this->value('log', $tableXML, 'false'),
220 'archive' => $this->value('archive', $tableXML, 'false'),
224 foreach ($tableXML->field
as $fieldXML) {
225 if ($this->value('drop', $fieldXML, 0) > 0 and $this->value('drop', $fieldXML, 0) <= $this->buildVersion
) {
229 if ($this->value('add', $fieldXML, 0) <= $this->buildVersion
) {
230 $this->getField($fieldXML, $fields);
234 $table['fields'] = &$fields;
236 if ($this->value('primaryKey', $tableXML)) {
237 $this->getPrimaryKey($tableXML->primaryKey
, $fields, $table);
240 if ($this->value('index', $tableXML)) {
242 foreach ($tableXML->index
as $indexXML) {
243 if ($this->value('drop', $indexXML, 0) > 0 and $this->value('drop', $indexXML, 0) <= $this->buildVersion
) {
247 $this->getIndex($indexXML, $fields, $index);
249 CRM_Core_BAO_SchemaHandler
::addIndexSignature($name, $index);
250 $table['index'] = &$index;
253 if ($this->value('foreignKey', $tableXML)) {
255 foreach ($tableXML->foreignKey
as $foreignXML) {
257 if ($this->value('drop', $foreignXML, 0) > 0 and $this->value('drop', $foreignXML, 0) <= $this->buildVersion
) {
260 if ($this->value('add', $foreignXML, 0) <= $this->buildVersion
) {
261 $this->getForeignKey($foreignXML, $fields, $foreign, $name);
264 $table['foreignKey'] = &$foreign;
267 if ($this->value('dynamicForeignKey', $tableXML)) {
268 $dynamicForeign = array();
269 foreach ($tableXML->dynamicForeignKey
as $foreignXML) {
270 if ($this->value('drop', $foreignXML, 0) > 0 and $this->value('drop', $foreignXML, 0) <= $this->buildVersion
) {
273 if ($this->value('add', $foreignXML, 0) <= $this->buildVersion
) {
274 $this->getDynamicForeignKey($foreignXML, $dynamicForeign, $name);
277 $table['dynamicForeignKey'] = $dynamicForeign;
280 $tables[$name] = &$table;
287 public function getField(&$fieldXML, &$fields) {
288 $name = trim((string ) $fieldXML->name
);
289 $field = array('name' => $name, 'localizable' => ((bool) $fieldXML->localizable
) ?
1 : 0);
290 $type = (string ) $fieldXML->type
;
294 $field['length'] = (int) $fieldXML->length
;
295 $field['sqlType'] = "$type({$field['length']})";
296 $field['phpType'] = 'string';
297 $field['crmType'] = 'CRM_Utils_Type::T_STRING';
298 $field['size'] = $this->getSize($fieldXML);
302 $field['sqlType'] = $field['phpType'] = $type;
303 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
304 // CRM-13497 see fixme below
305 $field['rows'] = isset($fieldXML->html
) ?
$this->value('rows', $fieldXML->html
) : NULL;
306 $field['cols'] = isset($fieldXML->html
) ?
$this->value('cols', $fieldXML->html
) : NULL;
312 $field['sqlType'] = $field['phpType'] = $type;
313 $field['crmType'] = 'CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME';
317 // need this case since some versions of mysql do not have boolean as a valid column type and hence it
318 // is changed to tinyint. hopefully after 2 yrs this case can be removed.
319 $field['sqlType'] = 'tinyint';
320 $field['phpType'] = $type;
321 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
325 $length = $fieldXML->length ?
$fieldXML->length
: '20,2';
326 $field['sqlType'] = 'decimal(' . $length . ')';
327 $field['phpType'] = 'float';
328 $field['crmType'] = 'CRM_Utils_Type::T_MONEY';
329 $field['precision'] = $length;
333 $field['sqlType'] = 'double';
334 $field['phpType'] = 'float';
335 $field['crmType'] = 'CRM_Utils_Type::T_FLOAT';
339 $field['phpType'] = $this->value('phpType', $fieldXML, $type);
340 $field['sqlType'] = $type;
341 if ($type == 'int unsigned') {
342 $field['crmType'] = 'CRM_Utils_Type::T_INT';
345 $field['crmType'] = $this->value('crmType', $fieldXML, 'CRM_Utils_Type::T_' . strtoupper($type));
350 $field['required'] = $this->value('required', $fieldXML);
351 $field['collate'] = $this->value('collate', $fieldXML);
352 $field['comment'] = $this->value('comment', $fieldXML);
353 $field['default'] = $this->value('default', $fieldXML);
354 $field['import'] = $this->value('import', $fieldXML);
355 if ($this->value('export', $fieldXML)) {
356 $field['export'] = $this->value('export', $fieldXML);
359 $field['export'] = $this->value('import', $fieldXML);
361 $field['rule'] = $this->value('rule', $fieldXML);
362 $field['title'] = $this->value('title', $fieldXML);
363 if (!$field['title']) {
364 $field['title'] = $this->composeTitle($name);
366 $field['headerPattern'] = $this->value('headerPattern', $fieldXML);
367 $field['dataPattern'] = $this->value('dataPattern', $fieldXML);
368 $field['uniqueName'] = $this->value('uniqueName', $fieldXML);
369 $field['serialize'] = $this->value('serialize', $fieldXML);
370 $field['html'] = $this->value('html', $fieldXML);
371 if (!empty($field['html'])) {
372 $validOptions = array(
376 /* Fixme: prior to CRM-13497 these were in a flat structure
377 // CRM-13497 moved them to be nested within 'html' but there's no point
378 // making that change in the DAOs right now since we are in the process of
379 // moving to docrtine anyway.
380 // So translating from nested xml back to flat structure for now.
385 $field['html'] = array();
386 foreach ($validOptions as $htmlOption) {
387 if (!empty($fieldXML->html
->$htmlOption)) {
388 $field['html'][$htmlOption] = $this->value($htmlOption, $fieldXML->html
);
393 // in multilingual context popup, we need extra information to create appropriate widget
394 if ($fieldXML->localizable
) {
395 if (isset($fieldXML->html
)) {
396 $field['widget'] = (array) $fieldXML->html
;
400 $field['widget'] = array('type' => 'Text');
402 if (isset($fieldXML->required
)) {
403 $field['widget']['required'] = $this->value('required', $fieldXML);
407 $field['pseudoconstant'] = $this->value('pseudoconstant', $fieldXML);
408 if (!empty($field['pseudoconstant'])) {
409 //ok this is a bit long-winded but it gets there & is consistent with above approach
410 $field['pseudoconstant'] = array();
411 $validOptions = array(
412 // Fields can specify EITHER optionGroupName OR table, not both
413 // (since declaring optionGroupName means we are using the civicrm_option_value table)
416 // If table is specified, keyColumn and labelColumn are also required
419 // Non-translated machine name for programmatic lookup. Defaults to 'name' if that column exists
421 // Where clause snippet (will be joined to the rest of the query with AND operator)
423 // callback function incase of static arrays
425 // Path to options edit form
428 foreach ($validOptions as $pseudoOption) {
429 if (!empty($fieldXML->pseudoconstant
->$pseudoOption)) {
430 $field['pseudoconstant'][$pseudoOption] = $this->value($pseudoOption, $fieldXML->pseudoconstant
);
433 if (!isset($field['pseudoconstant']['optionEditPath']) && !empty($field['pseudoconstant']['optionGroupName'])) {
434 $field['pseudoconstant']['optionEditPath'] = 'civicrm/admin/options/' . $field['pseudoconstant']['optionGroupName'];
436 // For now, fields that have option lists that are not in the db can simply
437 // declare an empty pseudoconstant tag and we'll add this placeholder.
438 // That field's BAO::buildOptions fn will need to be responsible for generating the option list
439 if (empty($field['pseudoconstant'])) {
440 $field['pseudoconstant'] = 'not in database';
443 $fields[$name] = &$field;
447 * @param string $name
451 public function composeTitle($name) {
452 $names = explode('_', strtolower($name));
454 for ($i = 0; $i < count($names); $i++
) {
455 if ($names[$i] === 'id' ||
$names[$i] === 'is') {
456 // id's do not get titles
460 if ($names[$i] === 'im') {
464 $names[$i] = ucfirst(trim($names[$i]));
467 $title = $title . ' ' . $names[$i];
473 * @param object $primaryXML
474 * @param array $fields
475 * @param array $table
477 public function getPrimaryKey(&$primaryXML, &$fields, &$table) {
478 $name = trim((string ) $primaryXML->name
);
480 // set the autoincrement property of the field
481 $auto = $this->value('autoincrement', $primaryXML);
482 if (isset($fields[$name])) {
483 $fields[$name]['autoincrement'] = $auto;
485 $fields[$name]['autoincrement'] = $auto;
488 'autoincrement' => $auto,
492 foreach ($primaryXML->fieldName
as $v) {
493 $fieldName = (string) ($v);
494 $length = (string) ($v['length']);
495 if (strlen($length) > 0) {
496 $fieldName = "$fieldName($length)";
498 $primaryKey['field'][] = $fieldName;
501 // when field array is empty set it to the name of the primary key.
502 if (empty($primaryKey['field'])) {
503 $primaryKey['field'][] = $name;
506 // all fieldnames have to be defined and should exist in schema.
507 foreach ($primaryKey['field'] as $fieldName) {
509 echo "Invalid field defination for index $name\n";
512 $parenOffset = strpos($fieldName, '(');
513 if ($parenOffset > 0) {
514 $fieldName = substr($fieldName, 0, $parenOffset);
516 if (!array_key_exists($fieldName, $fields)) {
517 echo "Table does not contain $fieldName\n";
523 $table['primaryKey'] = &$primaryKey;
531 public function getIndex(&$indexXML, &$fields, &$indices) {
532 //echo "\n\n*******************************************************\n";
533 //echo "entering getIndex\n";
536 // empty index name is fine
537 $indexName = trim((string) $indexXML->name
);
538 $index['name'] = $indexName;
539 $index['field'] = array();
542 foreach ($indexXML->fieldName
as $v) {
543 $fieldName = (string) ($v);
544 $length = (string) ($v['length']);
545 if (strlen($length) > 0) {
546 $fieldName = "$fieldName($length)";
548 $index['field'][] = $fieldName;
551 $index['localizable'] = FALSE;
552 foreach ($index['field'] as $fieldName) {
553 if (isset($fields[$fieldName]) and $fields[$fieldName]['localizable']) {
554 $index['localizable'] = TRUE;
559 // check for unique index
560 if ($this->value('unique', $indexXML)) {
561 $index['unique'] = TRUE;
564 // field array cannot be empty
565 if (empty($index['field'])) {
566 echo "No fields defined for index $indexName\n";
570 // all fieldnames have to be defined and should exist in schema.
571 foreach ($index['field'] as $fieldName) {
573 echo "Invalid field defination for index $indexName\n";
576 $parenOffset = strpos($fieldName, '(');
577 if ($parenOffset > 0) {
578 $fieldName = substr($fieldName, 0, $parenOffset);
580 if (!array_key_exists($fieldName, $fields)) {
581 echo "Table does not contain $fieldName\n";
586 $indices[$indexName] = &$index;
592 * @param $foreignKeys
593 * @param string $currentTableName
595 public function getForeignKey(&$foreignXML, &$fields, &$foreignKeys, &$currentTableName) {
596 $name = trim((string ) $foreignXML->name
);
598 /** need to make sure there is a field of type name */
599 if (!array_key_exists($name, $fields)) {
600 echo "foreign $name in $currentTableName does not have a field definition, ignoring\n";
604 /** need to check for existence of table and key **/
605 $table = trim($this->value('table', $foreignXML));
609 'uniqName' => "FK_{$currentTableName}_{$name}",
610 'key' => trim($this->value('key', $foreignXML)),
611 'import' => $this->value('import', $foreignXML, FALSE),
612 'export' => $this->value('import', $foreignXML, FALSE),
613 // we do this matching in a separate phase (resolveForeignKeys)
615 'onDelete' => $this->value('onDelete', $foreignXML, FALSE),
617 $foreignKeys[$name] = &$foreignKey;
622 * @param $dynamicForeignKeys
624 public function getDynamicForeignKey(&$foreignXML, &$dynamicForeignKeys) {
626 'idColumn' => trim($foreignXML->idColumn
),
627 'typeColumn' => trim($foreignXML->typeColumn
),
628 'key' => trim($this->value('key', $foreignXML)),
630 $dynamicForeignKeys[] = $foreignKey;
636 * @param null $default
638 * @return null|string
640 protected function value($key, &$object, $default = NULL) {
641 if (isset($object->$key)) {
642 return (string ) $object->$key;
650 * @param string $name
654 protected function checkAndAppend(&$attributes, &$object, $name, $pre = NULL, $post = NULL) {
655 if (!isset($object->$name)) {
659 $value = $pre . trim($object->$name) . $post;
660 $this->append($attributes, ' ', trim($value));
668 protected function append(&$str, $delim, $name) {
673 if (is_array($name)) {
674 foreach ($name as $n) {
691 $str .= $delim . $name;
697 * Sets the size property of a textfield.
699 * @param string $fieldXML
701 * @return null|string
703 protected function getSize($fieldXML) {
704 // Extract from <size> tag if supplied
705 if (!empty($fieldXML->html
) && $this->value('size', $fieldXML->html
)) {
706 return $this->value('size', $fieldXML->html
);
708 // Infer from <length> tag if <size> was not explicitly set or was invalid
709 // This map is slightly different from CRM_Core_Form_Renderer::$_sizeMapper
710 // Because we usually want fields to render as smaller than their maxlength
720 foreach ($sizes as $length => $name) {
721 if ($fieldXML->length
<= $length) {
722 return "CRM_Utils_Type::$name";
725 return 'CRM_Utils_Type::HUGE';