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['sqlType'] = $field['phpType'] = $type;
340 if ($type == 'int unsigned') {
341 $field['crmType'] = 'CRM_Utils_Type::T_INT';
344 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
349 $field['required'] = $this->value('required', $fieldXML);
350 $field['collate'] = $this->value('collate', $fieldXML);
351 $field['comment'] = $this->value('comment', $fieldXML);
352 $field['default'] = $this->value('default', $fieldXML);
353 $field['import'] = $this->value('import', $fieldXML);
354 if ($this->value('export', $fieldXML)) {
355 $field['export'] = $this->value('export', $fieldXML);
358 $field['export'] = $this->value('import', $fieldXML);
360 $field['rule'] = $this->value('rule', $fieldXML);
361 $field['title'] = $this->value('title', $fieldXML);
362 if (!$field['title']) {
363 $field['title'] = $this->composeTitle($name);
365 $field['headerPattern'] = $this->value('headerPattern', $fieldXML);
366 $field['dataPattern'] = $this->value('dataPattern', $fieldXML);
367 $field['uniqueName'] = $this->value('uniqueName', $fieldXML);
368 $field['serialize'] = $this->value('serialize', $fieldXML);
369 $field['html'] = $this->value('html', $fieldXML);
370 if (!empty($field['html'])) {
371 $validOptions = array(
374 /* Fixme: prior to CRM-13497 these were in a flat structure
375 // CRM-13497 moved them to be nested within 'html' but there's no point
376 // making that change in the DAOs right now since we are in the process of
377 // moving to docrtine anyway.
378 // So translating from nested xml back to flat structure for now.
383 $field['html'] = array();
384 foreach ($validOptions as $htmlOption) {
385 if (!empty($fieldXML->html
->$htmlOption)) {
386 $field['html'][$htmlOption] = $this->value($htmlOption, $fieldXML->html
);
391 // in multilingual context popup, we need extra information to create appropriate widget
392 if ($fieldXML->localizable
) {
393 if (isset($fieldXML->html
)) {
394 $field['widget'] = (array) $fieldXML->html
;
398 $field['widget'] = array('type' => 'Text');
400 if (isset($fieldXML->required
)) {
401 $field['widget']['required'] = $this->value('required', $fieldXML);
405 $field['pseudoconstant'] = $this->value('pseudoconstant', $fieldXML);
406 if (!empty($field['pseudoconstant'])) {
407 //ok this is a bit long-winded but it gets there & is consistent with above approach
408 $field['pseudoconstant'] = array();
409 $validOptions = array(
410 // Fields can specify EITHER optionGroupName OR table, not both
411 // (since declaring optionGroupName means we are using the civicrm_option_value table)
414 // If table is specified, keyColumn and labelColumn are also required
417 // Non-translated machine name for programmatic lookup. Defaults to 'name' if that column exists
419 // Where clause snippet (will be joined to the rest of the query with AND operator)
421 // callback function incase of static arrays
423 // Path to options edit form
426 foreach ($validOptions as $pseudoOption) {
427 if (!empty($fieldXML->pseudoconstant
->$pseudoOption)) {
428 $field['pseudoconstant'][$pseudoOption] = $this->value($pseudoOption, $fieldXML->pseudoconstant
);
431 if (!isset($field['pseudoconstant']['optionEditPath']) && !empty($field['pseudoconstant']['optionGroupName'])) {
432 $field['pseudoconstant']['optionEditPath'] = 'civicrm/admin/options/' . $field['pseudoconstant']['optionGroupName'];
434 // For now, fields that have option lists that are not in the db can simply
435 // declare an empty pseudoconstant tag and we'll add this placeholder.
436 // That field's BAO::buildOptions fn will need to be responsible for generating the option list
437 if (empty($field['pseudoconstant'])) {
438 $field['pseudoconstant'] = 'not in database';
441 $fields[$name] = &$field;
445 * @param string $name
449 public function composeTitle($name) {
450 $names = explode('_', strtolower($name));
452 for ($i = 0; $i < count($names); $i++
) {
453 if ($names[$i] === 'id' ||
$names[$i] === 'is') {
454 // id's do not get titles
458 if ($names[$i] === 'im') {
462 $names[$i] = ucfirst(trim($names[$i]));
465 $title = $title . ' ' . $names[$i];
471 * @param object $primaryXML
472 * @param array $fields
473 * @param array $table
475 public function getPrimaryKey(&$primaryXML, &$fields, &$table) {
476 $name = trim((string ) $primaryXML->name
);
478 // set the autoincrement property of the field
479 $auto = $this->value('autoincrement', $primaryXML);
480 if (isset($fields[$name])) {
481 $fields[$name]['autoincrement'] = $auto;
483 $fields[$name]['autoincrement'] = $auto;
486 'autoincrement' => $auto,
490 foreach ($primaryXML->fieldName
as $v) {
491 $fieldName = (string) ($v);
492 $length = (string) ($v['length']);
493 if (strlen($length) > 0) {
494 $fieldName = "$fieldName($length)";
496 $primaryKey['field'][] = $fieldName;
499 // when field array is empty set it to the name of the primary key.
500 if (empty($primaryKey['field'])) {
501 $primaryKey['field'][] = $name;
504 // all fieldnames have to be defined and should exist in schema.
505 foreach ($primaryKey['field'] as $fieldName) {
507 echo "Invalid field defination for index $name\n";
510 $parenOffset = strpos($fieldName, '(');
511 if ($parenOffset > 0) {
512 $fieldName = substr($fieldName, 0, $parenOffset);
514 if (!array_key_exists($fieldName, $fields)) {
515 echo "Table does not contain $fieldName\n";
521 $table['primaryKey'] = &$primaryKey;
529 public function getIndex(&$indexXML, &$fields, &$indices) {
530 //echo "\n\n*******************************************************\n";
531 //echo "entering getIndex\n";
534 // empty index name is fine
535 $indexName = trim((string) $indexXML->name
);
536 $index['name'] = $indexName;
537 $index['field'] = array();
540 foreach ($indexXML->fieldName
as $v) {
541 $fieldName = (string) ($v);
542 $length = (string) ($v['length']);
543 if (strlen($length) > 0) {
544 $fieldName = "$fieldName($length)";
546 $index['field'][] = $fieldName;
549 $index['localizable'] = FALSE;
550 foreach ($index['field'] as $fieldName) {
551 if (isset($fields[$fieldName]) and $fields[$fieldName]['localizable']) {
552 $index['localizable'] = TRUE;
557 // check for unique index
558 if ($this->value('unique', $indexXML)) {
559 $index['unique'] = TRUE;
562 // field array cannot be empty
563 if (empty($index['field'])) {
564 echo "No fields defined for index $indexName\n";
568 // all fieldnames have to be defined and should exist in schema.
569 foreach ($index['field'] as $fieldName) {
571 echo "Invalid field defination for index $indexName\n";
574 $parenOffset = strpos($fieldName, '(');
575 if ($parenOffset > 0) {
576 $fieldName = substr($fieldName, 0, $parenOffset);
578 if (!array_key_exists($fieldName, $fields)) {
579 echo "Table does not contain $fieldName\n";
584 $indices[$indexName] = &$index;
590 * @param $foreignKeys
591 * @param string $currentTableName
593 public function getForeignKey(&$foreignXML, &$fields, &$foreignKeys, &$currentTableName) {
594 $name = trim((string ) $foreignXML->name
);
596 /** need to make sure there is a field of type name */
597 if (!array_key_exists($name, $fields)) {
598 echo "foreign $name in $currentTableName does not have a field definition, ignoring\n";
602 /** need to check for existence of table and key **/
603 $table = trim($this->value('table', $foreignXML));
607 'uniqName' => "FK_{$currentTableName}_{$name}",
608 'key' => trim($this->value('key', $foreignXML)),
609 'import' => $this->value('import', $foreignXML, FALSE),
610 'export' => $this->value('import', $foreignXML, FALSE),
611 // we do this matching in a separate phase (resolveForeignKeys)
613 'onDelete' => $this->value('onDelete', $foreignXML, FALSE),
615 $foreignKeys[$name] = &$foreignKey;
620 * @param $dynamicForeignKeys
622 public function getDynamicForeignKey(&$foreignXML, &$dynamicForeignKeys) {
624 'idColumn' => trim($foreignXML->idColumn
),
625 'typeColumn' => trim($foreignXML->typeColumn
),
626 'key' => trim($this->value('key', $foreignXML)),
628 $dynamicForeignKeys[] = $foreignKey;
634 * @param null $default
636 * @return null|string
638 protected function value($key, &$object, $default = NULL) {
639 if (isset($object->$key)) {
640 return (string ) $object->$key;
648 * @param string $name
652 protected function checkAndAppend(&$attributes, &$object, $name, $pre = NULL, $post = NULL) {
653 if (!isset($object->$name)) {
657 $value = $pre . trim($object->$name) . $post;
658 $this->append($attributes, ' ', trim($value));
666 protected function append(&$str, $delim, $name) {
671 if (is_array($name)) {
672 foreach ($name as $n) {
689 $str .= $delim . $name;
695 * Sets the size property of a textfield.
697 * @param string $fieldXML
699 * @return null|string
701 protected function getSize($fieldXML) {
702 // Extract from <size> tag if supplied
703 if (!empty($fieldXML->html
) && $this->value('size', $fieldXML->html
)) {
704 return $this->value('size', $fieldXML->html
);
706 // Infer from <length> tag if <size> was not explicitly set or was invalid
707 // This map is slightly different from CRM_Core_Form_Renderer::$_sizeMapper
708 // Because we usually want fields to render as smaller than their maxlength
718 foreach ($sizes as $length => $name) {
719 if ($fieldXML->length
<= $length) {
720 return "CRM_Utils_Type::$name";
723 return 'CRM_Utils_Type::HUGE';