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) {
20 $this->buildVersion
= $buildVersion;
22 echo "Parsing schema description " . $schemaPath . "\n";
23 $dbXML = CRM_Core_CodeGen_Util_Xml
::parse($schemaPath);
25 echo "Extracting database information\n";
26 $this->database
= &$this->getDatabase($dbXML);
28 $this->classNames
= array();
30 # TODO: peel DAO-specific stuff out of getTables, and spec reading into its own class
31 echo "Extracting table information\n";
32 $this->tables
= $this->getTables($dbXML, $this->database
);
34 $this->resolveForeignKeys($this->tables
, $this->classNames
);
35 $this->tables
= $this->orderTables($this->tables
);
37 // add archive tables here
38 foreach ($this->tables
as $name => $table) {
39 if ($table['archive'] == 'true') {
40 $name = 'archive_' . $table['name'];
41 $table['name'] = $name;
42 $table['archive'] = 'false';
43 if (isset($table['foreignKey'])) {
44 foreach ($table['foreignKey'] as $fkName => $fkValue) {
45 if ($this->tables
[$fkValue['table']]['archive'] == 'true') {
46 $table['foreignKey'][$fkName]['table'] = 'archive_' . $table['foreignKey'][$fkName]['table'];
47 $table['foreignKey'][$fkName]['uniqName']
48 = str_replace('FK_', 'FK_archive_', $table['foreignKey'][$fkName]['uniqName']);
51 $archiveTables[$name] = $table;
62 public function &getDatabase(&$dbXML) {
63 $database = array('name' => trim((string ) $dbXML->name
));
66 $this->checkAndAppend($attributes, $dbXML, 'character_set', 'DEFAULT CHARACTER SET ', '');
67 $this->checkAndAppend($attributes, $dbXML, 'collate', 'COLLATE ', '');
68 $database['attributes'] = $attributes;
70 $tableAttributes_modern = $tableAttributes_simple = '';
71 $this->checkAndAppend($tableAttributes_modern, $dbXML, 'table_type', 'ENGINE=', '');
72 $this->checkAndAppend($tableAttributes_simple, $dbXML, 'table_type', 'TYPE=', '');
73 $database['tableAttributes_modern'] = trim($tableAttributes_modern . ' ' . $attributes);
74 $database['tableAttributes_simple'] = trim($tableAttributes_simple);
76 $database['comment'] = $this->value('comment', $dbXML, '');
87 public function getTables($dbXML, &$database) {
89 foreach ($dbXML->tables
as $tablesXML) {
90 foreach ($tablesXML->table
as $tableXML) {
91 if ($this->value('drop', $tableXML, 0) > 0 and $this->value('drop', $tableXML, 0) <= $this->buildVersion
) {
95 if ($this->value('add', $tableXML, 0) <= $this->buildVersion
) {
96 $this->getTable($tableXML, $database, $tables);
106 * @param string $classNames
108 public function resolveForeignKeys(&$tables, &$classNames) {
109 foreach (array_keys($tables) as $name) {
110 $this->resolveForeignKey($tables, $classNames, $name);
116 * @param string $classNames
117 * @param string $name
119 public function resolveForeignKey(&$tables, &$classNames, $name) {
120 if (!array_key_exists('foreignKey', $tables[$name])) {
124 foreach (array_keys($tables[$name]['foreignKey']) as $fkey) {
125 $ftable = $tables[$name]['foreignKey'][$fkey]['table'];
126 if (!array_key_exists($ftable, $classNames)) {
127 echo "$ftable is not a valid foreign key table in $name\n";
130 $tables[$name]['foreignKey'][$fkey]['className'] = $classNames[$ftable];
131 $tables[$name]['foreignKey'][$fkey]['fileName'] = str_replace('_', '/', $classNames[$ftable]) . '.php';
132 $tables[$name]['fields'][$fkey]['FKClassName'] = $classNames[$ftable];
141 public function orderTables(&$tables) {
144 while (!empty($tables)) {
145 foreach (array_keys($tables) as $name) {
146 if ($this->validTable($tables, $ordered, $name)) {
147 $ordered[$name] = $tables[$name];
148 unset($tables[$name]);
158 * @param string $name
162 public function validTable(&$tables, &$valid, $name) {
163 if (!array_key_exists('foreignKey', $tables[$name])) {
167 foreach (array_keys($tables[$name]['foreignKey']) as $fkey) {
168 $ftable = $tables[$name]['foreignKey'][$fkey]['table'];
169 if (!array_key_exists($ftable, $valid) && $ftable !== $name) {
181 public function getTable($tableXML, &$database, &$tables) {
182 $name = trim((string ) $tableXML->name
);
183 $klass = trim((string ) $tableXML->class);
184 $base = $this->value('base', $tableXML);
185 $sourceFile = "xml/schema/{$base}/{$klass}.xml";
186 $daoPath = "{$base}/DAO/";
187 $baoPath = __DIR__
. '/../../../' . str_replace(' ', '', "{$base}/BAO/");
188 $pre = str_replace('/', '_', $daoPath);
189 $this->classNames
[$name] = $pre . $klass;
191 $localizable = FALSE;
192 foreach ($tableXML->field
as $fieldXML) {
193 if ($fieldXML->localizable
) {
202 'sourceFile' => $sourceFile,
203 'fileName' => $klass . '.php',
204 'objectName' => $klass,
205 'labelName' => substr($name, 8),
206 'className' => $this->classNames
[$name],
207 'bao' => (file_exists($baoPath . $klass . '.php') ?
str_replace('DAO', 'BAO', $this->classNames
[$name]) : $this->classNames
[$name]),
209 'attributes_simple' => trim($database['tableAttributes_simple']),
210 'attributes_modern' => trim($database['tableAttributes_modern']),
211 'comment' => $this->value('comment', $tableXML),
212 'localizable' => $localizable,
213 'log' => $this->value('log', $tableXML, 'false'),
214 'archive' => $this->value('archive', $tableXML, 'false'),
218 foreach ($tableXML->field
as $fieldXML) {
219 if ($this->value('drop', $fieldXML, 0) > 0 and $this->value('drop', $fieldXML, 0) <= $this->buildVersion
) {
223 if ($this->value('add', $fieldXML, 0) <= $this->buildVersion
) {
224 $this->getField($fieldXML, $fields);
228 $table['fields'] = &$fields;
230 if ($this->value('primaryKey', $tableXML)) {
231 $this->getPrimaryKey($tableXML->primaryKey
, $fields, $table);
234 // some kind of refresh?
235 CRM_Core_Config
::singleton(FALSE);
236 if ($this->value('index', $tableXML)) {
238 foreach ($tableXML->index
as $indexXML) {
239 if ($this->value('drop', $indexXML, 0) > 0 and $this->value('drop', $indexXML, 0) <= $this->buildVersion
) {
243 $this->getIndex($indexXML, $fields, $index);
245 CRM_Core_BAO_SchemaHandler
::addIndexSignature($name, $index);
246 $table['index'] = &$index;
249 if ($this->value('foreignKey', $tableXML)) {
251 foreach ($tableXML->foreignKey
as $foreignXML) {
253 if ($this->value('drop', $foreignXML, 0) > 0 and $this->value('drop', $foreignXML, 0) <= $this->buildVersion
) {
256 if ($this->value('add', $foreignXML, 0) <= $this->buildVersion
) {
257 $this->getForeignKey($foreignXML, $fields, $foreign, $name);
260 $table['foreignKey'] = &$foreign;
263 if ($this->value('dynamicForeignKey', $tableXML)) {
264 $dynamicForeign = array();
265 foreach ($tableXML->dynamicForeignKey
as $foreignXML) {
266 if ($this->value('drop', $foreignXML, 0) > 0 and $this->value('drop', $foreignXML, 0) <= $this->buildVersion
) {
269 if ($this->value('add', $foreignXML, 0) <= $this->buildVersion
) {
270 $this->getDynamicForeignKey($foreignXML, $dynamicForeign, $name);
273 $table['dynamicForeignKey'] = $dynamicForeign;
276 $tables[$name] = &$table;
283 public function getField(&$fieldXML, &$fields) {
284 $name = trim((string ) $fieldXML->name
);
285 $field = array('name' => $name, 'localizable' => ((bool) $fieldXML->localizable
) ?
1 : 0);
286 $type = (string ) $fieldXML->type
;
290 $field['length'] = (int) $fieldXML->length
;
291 $field['sqlType'] = "$type({$field['length']})";
292 $field['phpType'] = 'string';
293 $field['crmType'] = 'CRM_Utils_Type::T_STRING';
294 $field['size'] = $this->getSize($fieldXML);
298 $field['sqlType'] = $field['phpType'] = $type;
299 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
300 // CRM-13497 see fixme below
301 $field['rows'] = isset($fieldXML->html
) ?
$this->value('rows', $fieldXML->html
) : NULL;
302 $field['cols'] = isset($fieldXML->html
) ?
$this->value('cols', $fieldXML->html
) : NULL;
308 $field['sqlType'] = $field['phpType'] = $type;
309 $field['crmType'] = 'CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME';
313 // need this case since some versions of mysql do not have boolean as a valid column type and hence it
314 // is changed to tinyint. hopefully after 2 yrs this case can be removed.
315 $field['sqlType'] = 'tinyint';
316 $field['phpType'] = $type;
317 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
321 $length = $fieldXML->length ?
$fieldXML->length
: '20,2';
322 $field['sqlType'] = 'decimal(' . $length . ')';
323 $field['phpType'] = 'float';
324 $field['crmType'] = 'CRM_Utils_Type::T_MONEY';
325 $field['precision'] = $length;
329 $field['sqlType'] = 'double';
330 $field['phpType'] = 'float';
331 $field['crmType'] = 'CRM_Utils_Type::T_FLOAT';
335 $field['sqlType'] = $field['phpType'] = $type;
336 if ($type == 'int unsigned') {
337 $field['crmType'] = 'CRM_Utils_Type::T_INT';
340 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
345 $field['required'] = $this->value('required', $fieldXML);
346 $field['collate'] = $this->value('collate', $fieldXML);
347 $field['comment'] = $this->value('comment', $fieldXML);
348 $field['default'] = $this->value('default', $fieldXML);
349 $field['import'] = $this->value('import', $fieldXML);
350 if ($this->value('export', $fieldXML)) {
351 $field['export'] = $this->value('export', $fieldXML);
354 $field['export'] = $this->value('import', $fieldXML);
356 $field['rule'] = $this->value('rule', $fieldXML);
357 $field['title'] = $this->value('title', $fieldXML);
358 if (!$field['title']) {
359 $field['title'] = $this->composeTitle($name);
361 $field['headerPattern'] = $this->value('headerPattern', $fieldXML);
362 $field['dataPattern'] = $this->value('dataPattern', $fieldXML);
363 $field['uniqueName'] = $this->value('uniqueName', $fieldXML);
364 $field['html'] = $this->value('html', $fieldXML);
365 if (!empty($field['html'])) {
366 $validOptions = array(
369 /* Fixme: prior to CRM-13497 these were in a flat structure
370 // CRM-13497 moved them to be nested within 'html' but there's no point
371 // making that change in the DAOs right now since we are in the process of
372 // moving to docrtine anyway.
373 // So translating from nested xml back to flat structure for now.
378 $field['html'] = array();
379 foreach ($validOptions as $htmlOption) {
380 if (!empty($fieldXML->html
->$htmlOption)) {
381 $field['html'][$htmlOption] = $this->value($htmlOption, $fieldXML->html
);
386 // in multilingual context popup, we need extra information to create appropriate widget
387 if ($fieldXML->localizable
) {
388 if (isset($fieldXML->html
)) {
389 $field['widget'] = (array) $fieldXML->html
;
393 $field['widget'] = array('type' => 'Text');
395 if (isset($fieldXML->required
)) {
396 $field['widget']['required'] = $this->value('required', $fieldXML);
400 $field['pseudoconstant'] = $this->value('pseudoconstant', $fieldXML);
401 if (!empty($field['pseudoconstant'])) {
402 //ok this is a bit long-winded but it gets there & is consistent with above approach
403 $field['pseudoconstant'] = array();
404 $validOptions = array(
405 // Fields can specify EITHER optionGroupName OR table, not both
406 // (since declaring optionGroupName means we are using the civicrm_option_value table)
409 // If table is specified, keyColumn and labelColumn are also required
412 // Non-translated machine name for programmatic lookup. Defaults to 'name' if that column exists
414 // Where clause snippet (will be joined to the rest of the query with AND operator)
416 // callback function incase of static arrays
418 // Path to options edit form
421 foreach ($validOptions as $pseudoOption) {
422 if (!empty($fieldXML->pseudoconstant
->$pseudoOption)) {
423 $field['pseudoconstant'][$pseudoOption] = $this->value($pseudoOption, $fieldXML->pseudoconstant
);
426 if (!isset($field['pseudoconstant']['optionEditPath']) && !empty($field['pseudoconstant']['optionGroupName'])) {
427 $field['pseudoconstant']['optionEditPath'] = 'civicrm/admin/options/' . $field['pseudoconstant']['optionGroupName'];
429 // For now, fields that have option lists that are not in the db can simply
430 // declare an empty pseudoconstant tag and we'll add this placeholder.
431 // That field's BAO::buildOptions fn will need to be responsible for generating the option list
432 if (empty($field['pseudoconstant'])) {
433 $field['pseudoconstant'] = 'not in database';
436 $fields[$name] = &$field;
440 * @param string $name
444 public function composeTitle($name) {
445 $names = explode('_', strtolower($name));
447 for ($i = 0; $i < count($names); $i++
) {
448 if ($names[$i] === 'id' ||
$names[$i] === 'is') {
449 // id's do not get titles
453 if ($names[$i] === 'im') {
457 $names[$i] = ucfirst(trim($names[$i]));
460 $title = $title . ' ' . $names[$i];
466 * @param object $primaryXML
467 * @param array $fields
468 * @param array $table
470 public function getPrimaryKey(&$primaryXML, &$fields, &$table) {
471 $name = trim((string ) $primaryXML->name
);
473 // set the autoincrement property of the field
474 $auto = $this->value('autoincrement', $primaryXML);
475 if (isset($fields[$name])) {
476 $fields[$name]['autoincrement'] = $auto;
478 $fields[$name]['autoincrement'] = $auto;
481 'autoincrement' => $auto,
485 foreach ($primaryXML->fieldName
as $v) {
486 $fieldName = (string) ($v);
487 $length = (string) ($v['length']);
488 if (strlen($length) > 0) {
489 $fieldName = "$fieldName($length)";
491 $primaryKey['field'][] = $fieldName;
494 // when field array is empty set it to the name of the primary key.
495 if (empty($primaryKey['field'])) {
496 $primaryKey['field'][] = $name;
499 // all fieldnames have to be defined and should exist in schema.
500 foreach ($primaryKey['field'] as $fieldName) {
502 echo "Invalid field defination for index $name\n";
505 $parenOffset = strpos($fieldName, '(');
506 if ($parenOffset > 0) {
507 $fieldName = substr($fieldName, 0, $parenOffset);
509 if (!array_key_exists($fieldName, $fields)) {
510 echo "Table does not contain $fieldName\n";
516 $table['primaryKey'] = &$primaryKey;
524 public function getIndex(&$indexXML, &$fields, &$indices) {
525 //echo "\n\n*******************************************************\n";
526 //echo "entering getIndex\n";
529 // empty index name is fine
530 $indexName = trim((string) $indexXML->name
);
531 $index['name'] = $indexName;
532 $index['field'] = array();
535 foreach ($indexXML->fieldName
as $v) {
536 $fieldName = (string) ($v);
537 $length = (string) ($v['length']);
538 if (strlen($length) > 0) {
539 $fieldName = "$fieldName($length)";
541 $index['field'][] = $fieldName;
544 $index['localizable'] = FALSE;
545 foreach ($index['field'] as $fieldName) {
546 if (isset($fields[$fieldName]) and $fields[$fieldName]['localizable']) {
547 $index['localizable'] = TRUE;
552 // check for unique index
553 if ($this->value('unique', $indexXML)) {
554 $index['unique'] = TRUE;
557 // field array cannot be empty
558 if (empty($index['field'])) {
559 echo "No fields defined for index $indexName\n";
563 // all fieldnames have to be defined and should exist in schema.
564 foreach ($index['field'] as $fieldName) {
566 echo "Invalid field defination for index $indexName\n";
569 $parenOffset = strpos($fieldName, '(');
570 if ($parenOffset > 0) {
571 $fieldName = substr($fieldName, 0, $parenOffset);
573 if (!array_key_exists($fieldName, $fields)) {
574 echo "Table does not contain $fieldName\n";
579 $indices[$indexName] = &$index;
585 * @param $foreignKeys
586 * @param string $currentTableName
588 public function getForeignKey(&$foreignXML, &$fields, &$foreignKeys, &$currentTableName) {
589 $name = trim((string ) $foreignXML->name
);
591 /** need to make sure there is a field of type name */
592 if (!array_key_exists($name, $fields)) {
593 echo "foreign $name in $currentTableName does not have a field definition, ignoring\n";
597 /** need to check for existence of table and key **/
598 $table = trim($this->value('table', $foreignXML));
602 'uniqName' => "FK_{$currentTableName}_{$name}",
603 'key' => trim($this->value('key', $foreignXML)),
604 'import' => $this->value('import', $foreignXML, FALSE),
605 'export' => $this->value('import', $foreignXML, FALSE),
606 // we do this matching in a separate phase (resolveForeignKeys)
608 'onDelete' => $this->value('onDelete', $foreignXML, FALSE),
610 $foreignKeys[$name] = &$foreignKey;
615 * @param $dynamicForeignKeys
617 public function getDynamicForeignKey(&$foreignXML, &$dynamicForeignKeys) {
619 'idColumn' => trim($foreignXML->idColumn
),
620 'typeColumn' => trim($foreignXML->typeColumn
),
621 'key' => trim($this->value('key', $foreignXML)),
623 $dynamicForeignKeys[] = $foreignKey;
629 * @param null $default
631 * @return null|string
633 protected function value($key, &$object, $default = NULL) {
634 if (isset($object->$key)) {
635 return (string ) $object->$key;
643 * @param string $name
647 protected function checkAndAppend(&$attributes, &$object, $name, $pre = NULL, $post = NULL) {
648 if (!isset($object->$name)) {
652 $value = $pre . trim($object->$name) . $post;
653 $this->append($attributes, ' ', trim($value));
661 protected function append(&$str, $delim, $name) {
666 if (is_array($name)) {
667 foreach ($name as $n) {
684 $str .= $delim . $name;
690 * Sets the size property of a textfield.
692 * @param string $fieldXML
694 * @return null|string
696 protected function getSize($fieldXML) {
697 // Extract from <size> tag if supplied
698 if (!empty($fieldXML->html
) && $this->value('size', $fieldXML->html
)) {
699 return $this->value('size', $fieldXML->html
);
701 // Infer from <length> tag if <size> was not explicitly set or was invalid
702 // This map is slightly different from CRM_Core_Form_Renderer::$_sizeMapper
703 // Because we usually want fields to render as smaller than their maxlength
713 foreach ($sizes as $length => $name) {
714 if ($fieldXML->length
<= $length) {
715 return "CRM_Utils_Type::$name";
718 return 'CRM_Utils_Type::HUGE';