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.
18 * @param bool $verbose
20 public function parse($schemaPath, $buildVersion, $verbose = TRUE) {
21 $this->buildVersion
= $buildVersion;
24 echo "Parsing schema description " . $schemaPath . "\n";
26 $dbXML = CRM_Core_CodeGen_Util_Xml
::parse($schemaPath);
29 echo "Extracting database information\n";
31 $this->database
= &$this->getDatabase($dbXML);
33 $this->classNames
= [];
35 // TODO: peel DAO-specific stuff out of getTables, and spec reading into its own class
37 echo "Extracting table information\n";
39 $this->tables
= $this->getTables($dbXML, $this->database
);
41 $this->resolveForeignKeys($this->tables
, $this->classNames
);
42 $this->tables
= $this->orderTables($this->tables
);
44 // add archive tables here
45 foreach ($this->tables
as $name => $table) {
46 if ($table['archive'] == 'true') {
47 $name = 'archive_' . $table['name'];
48 $table['name'] = $name;
49 $table['archive'] = 'false';
50 if (isset($table['foreignKey'])) {
51 foreach ($table['foreignKey'] as $fkName => $fkValue) {
52 if ($this->tables
[$fkValue['table']]['archive'] == 'true') {
53 $table['foreignKey'][$fkName]['table'] = 'archive_' . $table['foreignKey'][$fkName]['table'];
54 $table['foreignKey'][$fkName]['uniqName']
55 = str_replace('FK_', 'FK_archive_', $table['foreignKey'][$fkName]['uniqName']);
58 $archiveTables[$name] = $table;
69 public function &getDatabase(&$dbXML) {
70 $database = ['name' => trim((string ) $dbXML->name
)];
73 $this->checkAndAppend($attributes, $dbXML, 'character_set', 'DEFAULT CHARACTER SET ', '');
74 $this->checkAndAppend($attributes, $dbXML, 'collate', 'COLLATE ', '');
75 $database['attributes'] = $attributes;
77 $tableAttributes_modern = $tableAttributes_simple = '';
78 $this->checkAndAppend($tableAttributes_modern, $dbXML, 'table_type', 'ENGINE=', '');
79 $this->checkAndAppend($tableAttributes_simple, $dbXML, 'table_type', 'TYPE=', '');
80 $database['tableAttributes_modern'] = trim($tableAttributes_modern . ' ' . $attributes);
81 $database['tableAttributes_simple'] = trim($tableAttributes_simple);
83 $database['comment'] = $this->value('comment', $dbXML, '');
94 public function getTables($dbXML, &$database) {
96 foreach ($dbXML->tables
as $tablesXML) {
97 foreach ($tablesXML->table
as $tableXML) {
98 if ($this->value('drop', $tableXML, 0) > 0 && version_compare($this->value('drop', $tableXML, 0), $this->buildVersion
, '<=')) {
102 if (version_compare($this->value('add', $tableXML, 0), $this->buildVersion
, '<=')) {
103 $this->getTable($tableXML, $database, $tables);
113 * @param string $classNames
115 public function resolveForeignKeys(&$tables, &$classNames) {
116 foreach (array_keys($tables) as $name) {
117 $this->resolveForeignKey($tables, $classNames, $name);
123 * @param string $classNames
124 * @param string $name
126 public function resolveForeignKey(&$tables, &$classNames, $name) {
127 if (!array_key_exists('foreignKey', $tables[$name])) {
131 foreach (array_keys($tables[$name]['foreignKey']) as $fkey) {
132 $ftable = $tables[$name]['foreignKey'][$fkey]['table'];
133 if (!array_key_exists($ftable, $classNames)) {
134 echo "$ftable is not a valid foreign key table in $name\n";
137 $tables[$name]['foreignKey'][$fkey]['className'] = $classNames[$ftable];
138 $tables[$name]['foreignKey'][$fkey]['fileName'] = str_replace('_', '/', $classNames[$ftable]) . '.php';
139 $tables[$name]['fields'][$fkey]['FKClassName'] = $classNames[$ftable];
148 public function orderTables(&$tables) {
151 while (!empty($tables)) {
152 foreach (array_keys($tables) as $name) {
153 if ($this->validTable($tables, $ordered, $name)) {
154 $ordered[$name] = $tables[$name];
155 unset($tables[$name]);
165 * @param string $name
169 public function validTable(&$tables, &$valid, $name) {
170 if (!array_key_exists('foreignKey', $tables[$name])) {
174 foreach (array_keys($tables[$name]['foreignKey']) as $fkey) {
175 $ftable = $tables[$name]['foreignKey'][$fkey]['table'];
176 if (!array_key_exists($ftable, $valid) && $ftable !== $name) {
188 public function getTable($tableXML, &$database, &$tables) {
189 $name = trim((string ) $tableXML->name
);
190 $klass = trim((string ) $tableXML->class);
191 $base = $this->value('base', $tableXML);
192 $sourceFile = "xml/schema/{$base}/{$klass}.xml";
193 $daoPath = "{$base}/DAO/";
194 $baoPath = __DIR__
. '/../../../' . str_replace(' ', '', "{$base}/BAO/");
195 $useBao = $this->value('useBao', $tableXML, file_exists($baoPath . $klass . '.php'));
196 $pre = str_replace('/', '_', $daoPath);
197 $this->classNames
[$name] = $pre . $klass;
199 $localizable = FALSE;
200 foreach ($tableXML->field
as $fieldXML) {
201 if ($fieldXML->localizable
) {
207 $titleFromClass = preg_replace('/([a-z])([A-Z])/', '$1 $2', $klass);
211 'sourceFile' => $sourceFile,
212 'fileName' => $klass . '.php',
213 'objectName' => $klass,
214 'title' => $tableXML->title ??
$titleFromClass,
215 'titlePlural' => $tableXML->titlePlural ?? CRM_Utils_String
::pluralize($tableXML->title ??
$titleFromClass),
216 'icon' => $tableXML->icon ??
NULL,
217 'add' => $tableXML->add ??
NULL,
218 'labelName' => substr($name, 8),
219 'className' => $this->classNames
[$name],
220 'bao' => ($useBao ?
str_replace('DAO', 'BAO', $this->classNames
[$name]) : $this->classNames
[$name]),
222 'attributes_simple' => trim($database['tableAttributes_simple']),
223 'attributes_modern' => trim($database['tableAttributes_modern']),
224 'comment' => $this->value('comment', $tableXML),
225 'localizable' => $localizable,
226 'log' => $this->value('log', $tableXML, 'false'),
227 'archive' => $this->value('archive', $tableXML, 'false'),
231 foreach ($tableXML->field
as $fieldXML) {
232 if ($this->value('drop', $fieldXML, 0) > 0 && version_compare($this->value('drop', $fieldXML, 0), $this->buildVersion
, '<=')) {
236 if (version_compare($this->value('add', $fieldXML, 0), $this->buildVersion
, '<=')) {
237 $this->getField($fieldXML, $fields);
241 $table['fields'] = &$fields;
243 if ($this->value('primaryKey', $tableXML)) {
244 $this->getPrimaryKey($tableXML->primaryKey
, $fields, $table);
247 if ($this->value('index', $tableXML)) {
249 foreach ($tableXML->index
as $indexXML) {
250 if ($this->value('drop', $indexXML, 0) > 0 && version_compare($this->value('drop', $indexXML, 0), $this->buildVersion
, '<=')) {
254 $this->getIndex($indexXML, $fields, $index);
256 CRM_Core_BAO_SchemaHandler
::addIndexSignature($name, $index);
257 $table['index'] = &$index;
260 if ($this->value('foreignKey', $tableXML)) {
262 foreach ($tableXML->foreignKey
as $foreignXML) {
264 if ($this->value('drop', $foreignXML, 0) > 0 && version_compare($this->value('drop', $foreignXML, 0), $this->buildVersion
, '<=')) {
267 if (version_compare($this->value('add', $foreignXML, 0), $this->buildVersion
, '<=')) {
268 $this->getForeignKey($foreignXML, $fields, $foreign, $name);
271 $table['foreignKey'] = &$foreign;
274 if ($this->value('dynamicForeignKey', $tableXML)) {
275 $dynamicForeign = [];
276 foreach ($tableXML->dynamicForeignKey
as $foreignXML) {
277 if ($this->value('drop', $foreignXML, 0) > 0 && version_compare($this->value('drop', $foreignXML, 0), $this->buildVersion
, '<=')) {
280 if (version_compare($this->value('add', $foreignXML, 0), $this->buildVersion
, '<=')) {
281 $this->getDynamicForeignKey($foreignXML, $dynamicForeign, $name);
284 $table['dynamicForeignKey'] = $dynamicForeign;
287 $tables[$name] = &$table;
294 public function getField(&$fieldXML, &$fields) {
295 $name = trim((string ) $fieldXML->name
);
296 $field = ['name' => $name, 'localizable' => ((bool) $fieldXML->localizable
) ?
1 : 0];
297 $type = (string ) $fieldXML->type
;
301 $field['length'] = (int) $fieldXML->length
;
302 $field['sqlType'] = "$type({$field['length']})";
303 $field['phpType'] = 'string';
304 $field['crmType'] = 'CRM_Utils_Type::T_STRING';
305 $field['size'] = $this->getSize($fieldXML);
309 $field['sqlType'] = $field['phpType'] = $type;
310 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
311 // CRM-13497 see fixme below
312 $field['rows'] = isset($fieldXML->html
) ?
$this->value('rows', $fieldXML->html
) : NULL;
313 $field['cols'] = isset($fieldXML->html
) ?
$this->value('cols', $fieldXML->html
) : NULL;
319 $field['sqlType'] = $field['phpType'] = $type;
320 $field['crmType'] = 'CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME';
324 // need this case since some versions of mysql do not have boolean as a valid column type and hence it
325 // is changed to tinyint. hopefully after 2 yrs this case can be removed.
326 $field['sqlType'] = 'tinyint';
327 $field['phpType'] = 'bool';
328 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
332 $length = $fieldXML->length ?
$fieldXML->length
: '20,2';
333 $field['sqlType'] = 'decimal(' . $length . ')';
334 $field['phpType'] = 'float';
335 $field['crmType'] = 'CRM_Utils_Type::T_MONEY';
336 $field['precision'] = $length . ',';
340 $field['sqlType'] = 'double';
341 $field['phpType'] = 'float';
342 $field['crmType'] = 'CRM_Utils_Type::T_FLOAT';
346 $field['phpType'] = $this->value('phpType', $fieldXML, $type);
347 $field['sqlType'] = $type;
348 if ($type == 'int unsigned' ||
$type == 'tinyint') {
349 $field['phpType'] = 'int';
350 $field['crmType'] = 'CRM_Utils_Type::T_INT';
353 $field['crmType'] = $this->value('crmType', $fieldXML, 'CRM_Utils_Type::T_' . strtoupper($type));
358 $field['required'] = $this->value('required', $fieldXML);
359 $field['collate'] = $this->value('collate', $fieldXML);
360 $field['comment'] = $this->value('comment', $fieldXML);
361 $field['default'] = $this->value('default', $fieldXML);
362 $field['import'] = $this->value('import', $fieldXML);
363 if ($this->value('export', $fieldXML)) {
364 $field['export'] = $this->value('export', $fieldXML);
367 $field['export'] = $this->value('import', $fieldXML);
369 $field['rule'] = $this->value('rule', $fieldXML);
370 $field['title'] = $this->value('title', $fieldXML);
371 if (!$field['title']) {
372 $field['title'] = $this->composeTitle($name);
374 $field['headerPattern'] = $this->value('headerPattern', $fieldXML);
375 $field['dataPattern'] = $this->value('dataPattern', $fieldXML);
376 $field['uniqueName'] = $this->value('uniqueName', $fieldXML);
377 $field['uniqueTitle'] = $this->value('uniqueTitle', $fieldXML);
378 $field['serialize'] = $this->value('serialize', $fieldXML);
379 $field['html'] = $this->value('html', $fieldXML);
380 $field['contactType'] = $this->value('contactType', $fieldXML);
381 if (isset($fieldXML->permission
)) {
382 $field['permission'] = trim($this->value('permission', $fieldXML));
383 $field['permission'] = $field['permission'] ?
array_filter(array_map('trim', explode(',', $field['permission']))) : [];
384 if (isset($fieldXML->permission
->or)) {
385 $field['permission'][] = array_filter(array_map('trim', explode(',', $fieldXML->permission
->or)));
388 if (!empty($field['html'])) {
394 /* Fixme: prior to CRM-13497 these were in a flat structure
395 // CRM-13497 moved them to be nested within 'html' but there's no point
396 // making that change in the DAOs right now since we are in the process of
397 // moving to docrtine anyway.
398 // So translating from nested xml back to flat structure for now.
404 foreach ($validOptions as $htmlOption) {
405 if (!empty($fieldXML->html
->$htmlOption)) {
406 $field['html'][$htmlOption] = $this->value($htmlOption, $fieldXML->html
);
411 // in multilingual context popup, we need extra information to create appropriate widget
412 if ($fieldXML->localizable
) {
413 if (isset($fieldXML->html
)) {
414 $field['widget'] = (array) $fieldXML->html
;
418 $field['widget'] = ['type' => 'Text'];
420 if (isset($fieldXML->required
)) {
421 $field['widget']['required'] = $this->value('required', $fieldXML);
424 if (isset($fieldXML->localize_context
)) {
425 $field['localize_context'] = $fieldXML->localize_context
;
427 $field['add'] = $this->value('add', $fieldXML);
428 $field['pseudoconstant'] = $this->value('pseudoconstant', $fieldXML);
429 if (!empty($field['pseudoconstant'])) {
430 //ok this is a bit long-winded but it gets there & is consistent with above approach
431 $field['pseudoconstant'] = [];
433 // Fields can specify EITHER optionGroupName OR table, not both
434 // (since declaring optionGroupName means we are using the civicrm_option_value table)
437 // If table is specified, keyColumn and labelColumn are also required
440 // Non-translated machine name for programmatic lookup. Defaults to 'name' if that column exists
442 // Column to fetch in "abbreviate" context
444 // Where clause snippet (will be joined to the rest of the query with AND operator)
446 // callback function incase of static arrays
448 // Path to options edit form
451 foreach ($validOptions as $pseudoOption) {
452 if (!empty($fieldXML->pseudoconstant
->$pseudoOption)) {
453 $field['pseudoconstant'][$pseudoOption] = $this->value($pseudoOption, $fieldXML->pseudoconstant
);
456 if (!isset($field['pseudoconstant']['optionEditPath']) && !empty($field['pseudoconstant']['optionGroupName'])) {
457 $field['pseudoconstant']['optionEditPath'] = 'civicrm/admin/options/' . $field['pseudoconstant']['optionGroupName'];
459 // For now, fields that have option lists that are not in the db can simply
460 // declare an empty pseudoconstant tag and we'll add this placeholder.
461 // That field's BAO::buildOptions fn will need to be responsible for generating the option list
462 if (empty($field['pseudoconstant'])) {
463 $field['pseudoconstant'] = 'not in database';
466 $fields[$name] = &$field;
470 * @param string $name
474 public function composeTitle($name) {
475 $names = explode('_', strtolower($name));
477 for ($i = 0; $i < count($names); $i++
) {
478 if ($names[$i] === 'id' ||
$names[$i] === 'is') {
479 // id's do not get titles
483 if ($names[$i] === 'im') {
487 $names[$i] = ucfirst(trim($names[$i]));
490 $title = $title . ' ' . $names[$i];
496 * @param object $primaryXML
497 * @param array $fields
498 * @param array $table
500 public function getPrimaryKey(&$primaryXML, &$fields, &$table) {
501 $name = trim((string ) $primaryXML->name
);
503 // set the autoincrement property of the field
504 $auto = $this->value('autoincrement', $primaryXML);
505 if (isset($fields[$name])) {
506 $fields[$name]['autoincrement'] = $auto;
508 $fields[$name]['autoincrement'] = $auto;
511 'autoincrement' => $auto,
515 foreach ($primaryXML->fieldName
as $v) {
516 $fieldName = (string) ($v);
517 $length = (string) ($v['length']);
518 if (strlen($length) > 0) {
519 $fieldName = "$fieldName($length)";
521 $primaryKey['field'][] = $fieldName;
524 // when field array is empty set it to the name of the primary key.
525 if (empty($primaryKey['field'])) {
526 $primaryKey['field'][] = $name;
529 // all fieldnames have to be defined and should exist in schema.
530 foreach ($primaryKey['field'] as $fieldName) {
532 echo "Invalid field defination for index $name\n";
535 $parenOffset = strpos($fieldName, '(');
536 if ($parenOffset > 0) {
537 $fieldName = substr($fieldName, 0, $parenOffset);
539 if (!array_key_exists($fieldName, $fields)) {
540 echo "Table does not contain $fieldName\n";
546 $table['primaryKey'] = &$primaryKey;
554 public function getIndex(&$indexXML, &$fields, &$indices) {
555 //echo "\n\n*******************************************************\n";
556 //echo "entering getIndex\n";
559 // empty index name is fine
560 $indexName = trim((string) $indexXML->name
);
561 $index['name'] = $indexName;
562 $index['field'] = [];
565 foreach ($indexXML->fieldName
as $v) {
566 $fieldName = (string) ($v);
567 $length = (string) ($v['length']);
568 if (strlen($length) > 0) {
569 $fieldName = "$fieldName($length)";
571 $index['field'][] = $fieldName;
574 $index['localizable'] = FALSE;
575 foreach ($index['field'] as $fieldName) {
576 if (isset($fields[$fieldName]) and $fields[$fieldName]['localizable']) {
577 $index['localizable'] = TRUE;
582 // check for unique index
583 if ($this->value('unique', $indexXML)) {
584 $index['unique'] = TRUE;
587 // field array cannot be empty
588 if (empty($index['field'])) {
589 echo "No fields defined for index $indexName\n";
593 // all fieldnames have to be defined and should exist in schema.
594 foreach ($index['field'] as $fieldName) {
596 echo "Invalid field defination for index $indexName\n";
599 $parenOffset = strpos($fieldName, '(');
600 if ($parenOffset > 0) {
601 $fieldName = substr($fieldName, 0, $parenOffset);
603 if (!array_key_exists($fieldName, $fields)) {
604 echo "Table does not contain $fieldName\n";
609 $indices[$indexName] = &$index;
615 * @param $foreignKeys
616 * @param string $currentTableName
618 public function getForeignKey(&$foreignXML, &$fields, &$foreignKeys, &$currentTableName) {
619 $name = trim((string ) $foreignXML->name
);
621 /** need to make sure there is a field of type name */
622 if (!array_key_exists($name, $fields)) {
623 echo "foreign $name in $currentTableName does not have a field definition, ignoring\n";
627 /** need to check for existence of table and key **/
628 $table = trim($this->value('table', $foreignXML));
632 'uniqName' => "FK_{$currentTableName}_{$name}",
633 'key' => trim($this->value('key', $foreignXML)),
634 'import' => $this->value('import', $foreignXML, FALSE),
635 'export' => $this->value('import', $foreignXML, FALSE),
636 // we do this matching in a separate phase (resolveForeignKeys)
638 'onDelete' => $this->value('onDelete', $foreignXML, FALSE),
640 $foreignKeys[$name] = &$foreignKey;
645 * @param $dynamicForeignKeys
647 public function getDynamicForeignKey(&$foreignXML, &$dynamicForeignKeys) {
649 'idColumn' => trim($foreignXML->idColumn
),
650 'typeColumn' => trim($foreignXML->typeColumn
),
651 'key' => trim($this->value('key', $foreignXML)),
653 $dynamicForeignKeys[] = $foreignKey;
659 * @param null $default
661 * @return null|string
663 protected function value($key, &$object, $default = NULL) {
664 if (isset($object->$key)) {
665 return (string ) $object->$key;
673 * @param string $name
677 protected function checkAndAppend(&$attributes, &$object, $name, $pre = NULL, $post = NULL) {
678 if (!isset($object->$name)) {
682 $value = $pre . trim($object->$name) . $post;
683 $this->append($attributes, ' ', trim($value));
691 protected function append(&$str, $delim, $name) {
696 if (is_array($name)) {
697 foreach ($name as $n) {
714 $str .= $delim . $name;
720 * Sets the size property of a textfield.
722 * @param string $fieldXML
724 * @return null|string
726 protected function getSize($fieldXML) {
727 // Extract from <size> tag if supplied
728 if (!empty($fieldXML->html
) && $this->value('size', $fieldXML->html
)) {
729 return $this->value('size', $fieldXML->html
);
731 // Infer from <length> tag if <size> was not explicitly set or was invalid
732 // This map is slightly different from CRM_Core_Form_Renderer::$_sizeMapper
733 // Because we usually want fields to render as smaller than their maxlength
743 foreach ($sizes as $length => $name) {
744 if ($fieldXML->length
<= $length) {
745 return "CRM_Utils_Type::$name";
748 return 'CRM_Utils_Type::HUGE';