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 $pre = str_replace('/', '_', $daoPath);
196 $this->classNames
[$name] = $pre . $klass;
198 $localizable = FALSE;
199 foreach ($tableXML->field
as $fieldXML) {
200 if ($fieldXML->localizable
) {
209 'sourceFile' => $sourceFile,
210 'fileName' => $klass . '.php',
211 'objectName' => $klass,
212 'labelName' => substr($name, 8),
213 'className' => $this->classNames
[$name],
214 'bao' => (file_exists($baoPath . $klass . '.php') ?
str_replace('DAO', 'BAO', $this->classNames
[$name]) : $this->classNames
[$name]),
216 'attributes_simple' => trim($database['tableAttributes_simple']),
217 'attributes_modern' => trim($database['tableAttributes_modern']),
218 'comment' => $this->value('comment', $tableXML),
219 'localizable' => $localizable,
220 'log' => $this->value('log', $tableXML, 'false'),
221 'archive' => $this->value('archive', $tableXML, 'false'),
225 foreach ($tableXML->field
as $fieldXML) {
226 if ($this->value('drop', $fieldXML, 0) > 0 && version_compare($this->value('drop', $fieldXML, 0), $this->buildVersion
, '<=')) {
230 if (version_compare($this->value('add', $fieldXML, 0), $this->buildVersion
, '<=')) {
231 $this->getField($fieldXML, $fields);
235 $table['fields'] = &$fields;
237 if ($this->value('primaryKey', $tableXML)) {
238 $this->getPrimaryKey($tableXML->primaryKey
, $fields, $table);
241 if ($this->value('index', $tableXML)) {
243 foreach ($tableXML->index
as $indexXML) {
244 if ($this->value('drop', $indexXML, 0) > 0 && version_compare($this->value('drop', $indexXML, 0), $this->buildVersion
, '<=')) {
248 $this->getIndex($indexXML, $fields, $index);
250 CRM_Core_BAO_SchemaHandler
::addIndexSignature($name, $index);
251 $table['index'] = &$index;
254 if ($this->value('foreignKey', $tableXML)) {
256 foreach ($tableXML->foreignKey
as $foreignXML) {
258 if ($this->value('drop', $foreignXML, 0) > 0 && version_compare($this->value('drop', $foreignXML, 0), $this->buildVersion
, '<=')) {
261 if (version_compare($this->value('add', $foreignXML, 0), $this->buildVersion
, '<=')) {
262 $this->getForeignKey($foreignXML, $fields, $foreign, $name);
265 $table['foreignKey'] = &$foreign;
268 if ($this->value('dynamicForeignKey', $tableXML)) {
269 $dynamicForeign = [];
270 foreach ($tableXML->dynamicForeignKey
as $foreignXML) {
271 if ($this->value('drop', $foreignXML, 0) > 0 && version_compare($this->value('drop', $foreignXML, 0), $this->buildVersion
, '<=')) {
274 if (version_compare($this->value('add', $foreignXML, 0), $this->buildVersion
, '<=')) {
275 $this->getDynamicForeignKey($foreignXML, $dynamicForeign, $name);
278 $table['dynamicForeignKey'] = $dynamicForeign;
281 $tables[$name] = &$table;
288 public function getField(&$fieldXML, &$fields) {
289 $name = trim((string ) $fieldXML->name
);
290 $field = ['name' => $name, 'localizable' => ((bool) $fieldXML->localizable
) ?
1 : 0];
291 $type = (string ) $fieldXML->type
;
295 $field['length'] = (int) $fieldXML->length
;
296 $field['sqlType'] = "$type({$field['length']})";
297 $field['phpType'] = 'string';
298 $field['crmType'] = 'CRM_Utils_Type::T_STRING';
299 $field['size'] = $this->getSize($fieldXML);
303 $field['sqlType'] = $field['phpType'] = $type;
304 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
305 // CRM-13497 see fixme below
306 $field['rows'] = isset($fieldXML->html
) ?
$this->value('rows', $fieldXML->html
) : NULL;
307 $field['cols'] = isset($fieldXML->html
) ?
$this->value('cols', $fieldXML->html
) : NULL;
313 $field['sqlType'] = $field['phpType'] = $type;
314 $field['crmType'] = 'CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME';
318 // need this case since some versions of mysql do not have boolean as a valid column type and hence it
319 // is changed to tinyint. hopefully after 2 yrs this case can be removed.
320 $field['sqlType'] = 'tinyint';
321 $field['phpType'] = 'bool';
322 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
326 $length = $fieldXML->length ?
$fieldXML->length
: '20,2';
327 $field['sqlType'] = 'decimal(' . $length . ')';
328 $field['phpType'] = 'float';
329 $field['crmType'] = 'CRM_Utils_Type::T_MONEY';
330 $field['precision'] = $length . ',';
334 $field['sqlType'] = 'double';
335 $field['phpType'] = 'float';
336 $field['crmType'] = 'CRM_Utils_Type::T_FLOAT';
340 $field['phpType'] = $this->value('phpType', $fieldXML, $type);
341 $field['sqlType'] = $type;
342 if ($type == 'int unsigned') {
343 $field['phpType'] = 'int';
344 $field['crmType'] = 'CRM_Utils_Type::T_INT';
347 $field['crmType'] = $this->value('crmType', $fieldXML, 'CRM_Utils_Type::T_' . strtoupper($type));
352 $field['required'] = $this->value('required', $fieldXML);
353 $field['collate'] = $this->value('collate', $fieldXML);
354 $field['comment'] = $this->value('comment', $fieldXML);
355 $field['default'] = $this->value('default', $fieldXML);
356 $field['import'] = $this->value('import', $fieldXML);
357 if ($this->value('export', $fieldXML)) {
358 $field['export'] = $this->value('export', $fieldXML);
361 $field['export'] = $this->value('import', $fieldXML);
363 $field['rule'] = $this->value('rule', $fieldXML);
364 $field['title'] = $this->value('title', $fieldXML);
365 if (!$field['title']) {
366 $field['title'] = $this->composeTitle($name);
368 $field['headerPattern'] = $this->value('headerPattern', $fieldXML);
369 $field['dataPattern'] = $this->value('dataPattern', $fieldXML);
370 $field['uniqueName'] = $this->value('uniqueName', $fieldXML);
371 $field['uniqueTitle'] = $this->value('uniqueTitle', $fieldXML);
372 $field['serialize'] = $this->value('serialize', $fieldXML);
373 $field['html'] = $this->value('html', $fieldXML);
374 if (isset($fieldXML->permission
)) {
375 $field['permission'] = trim($this->value('permission', $fieldXML));
376 $field['permission'] = $field['permission'] ?
array_filter(array_map('trim', explode(',', $field['permission']))) : [];
377 if (isset($fieldXML->permission
->or)) {
378 $field['permission'][] = array_filter(array_map('trim', explode(',', $fieldXML->permission
->or)));
381 if (!empty($field['html'])) {
386 /* Fixme: prior to CRM-13497 these were in a flat structure
387 // CRM-13497 moved them to be nested within 'html' but there's no point
388 // making that change in the DAOs right now since we are in the process of
389 // moving to docrtine anyway.
390 // So translating from nested xml back to flat structure for now.
396 foreach ($validOptions as $htmlOption) {
397 if (!empty($fieldXML->html
->$htmlOption)) {
398 $field['html'][$htmlOption] = $this->value($htmlOption, $fieldXML->html
);
403 // in multilingual context popup, we need extra information to create appropriate widget
404 if ($fieldXML->localizable
) {
405 if (isset($fieldXML->html
)) {
406 $field['widget'] = (array) $fieldXML->html
;
410 $field['widget'] = ['type' => 'Text'];
412 if (isset($fieldXML->required
)) {
413 $field['widget']['required'] = $this->value('required', $fieldXML);
416 if (isset($fieldXML->localize_context
)) {
417 $field['localize_context'] = $fieldXML->localize_context
;
419 $field['pseudoconstant'] = $this->value('pseudoconstant', $fieldXML);
420 if (!empty($field['pseudoconstant'])) {
421 //ok this is a bit long-winded but it gets there & is consistent with above approach
422 $field['pseudoconstant'] = [];
424 // Fields can specify EITHER optionGroupName OR table, not both
425 // (since declaring optionGroupName means we are using the civicrm_option_value table)
428 // If table is specified, keyColumn and labelColumn are also required
431 // Non-translated machine name for programmatic lookup. Defaults to 'name' if that column exists
433 // Column to fetch in "abbreviate" context
435 // Where clause snippet (will be joined to the rest of the query with AND operator)
437 // callback function incase of static arrays
439 // Path to options edit form
442 foreach ($validOptions as $pseudoOption) {
443 if (!empty($fieldXML->pseudoconstant
->$pseudoOption)) {
444 $field['pseudoconstant'][$pseudoOption] = $this->value($pseudoOption, $fieldXML->pseudoconstant
);
447 if (!isset($field['pseudoconstant']['optionEditPath']) && !empty($field['pseudoconstant']['optionGroupName'])) {
448 $field['pseudoconstant']['optionEditPath'] = 'civicrm/admin/options/' . $field['pseudoconstant']['optionGroupName'];
450 // For now, fields that have option lists that are not in the db can simply
451 // declare an empty pseudoconstant tag and we'll add this placeholder.
452 // That field's BAO::buildOptions fn will need to be responsible for generating the option list
453 if (empty($field['pseudoconstant'])) {
454 $field['pseudoconstant'] = 'not in database';
457 $fields[$name] = &$field;
461 * @param string $name
465 public function composeTitle($name) {
466 $names = explode('_', strtolower($name));
468 for ($i = 0; $i < count($names); $i++
) {
469 if ($names[$i] === 'id' ||
$names[$i] === 'is') {
470 // id's do not get titles
474 if ($names[$i] === 'im') {
478 $names[$i] = ucfirst(trim($names[$i]));
481 $title = $title . ' ' . $names[$i];
487 * @param object $primaryXML
488 * @param array $fields
489 * @param array $table
491 public function getPrimaryKey(&$primaryXML, &$fields, &$table) {
492 $name = trim((string ) $primaryXML->name
);
494 // set the autoincrement property of the field
495 $auto = $this->value('autoincrement', $primaryXML);
496 if (isset($fields[$name])) {
497 $fields[$name]['autoincrement'] = $auto;
499 $fields[$name]['autoincrement'] = $auto;
502 'autoincrement' => $auto,
506 foreach ($primaryXML->fieldName
as $v) {
507 $fieldName = (string) ($v);
508 $length = (string) ($v['length']);
509 if (strlen($length) > 0) {
510 $fieldName = "$fieldName($length)";
512 $primaryKey['field'][] = $fieldName;
515 // when field array is empty set it to the name of the primary key.
516 if (empty($primaryKey['field'])) {
517 $primaryKey['field'][] = $name;
520 // all fieldnames have to be defined and should exist in schema.
521 foreach ($primaryKey['field'] as $fieldName) {
523 echo "Invalid field defination for index $name\n";
526 $parenOffset = strpos($fieldName, '(');
527 if ($parenOffset > 0) {
528 $fieldName = substr($fieldName, 0, $parenOffset);
530 if (!array_key_exists($fieldName, $fields)) {
531 echo "Table does not contain $fieldName\n";
537 $table['primaryKey'] = &$primaryKey;
545 public function getIndex(&$indexXML, &$fields, &$indices) {
546 //echo "\n\n*******************************************************\n";
547 //echo "entering getIndex\n";
550 // empty index name is fine
551 $indexName = trim((string) $indexXML->name
);
552 $index['name'] = $indexName;
553 $index['field'] = [];
556 foreach ($indexXML->fieldName
as $v) {
557 $fieldName = (string) ($v);
558 $length = (string) ($v['length']);
559 if (strlen($length) > 0) {
560 $fieldName = "$fieldName($length)";
562 $index['field'][] = $fieldName;
565 $index['localizable'] = FALSE;
566 foreach ($index['field'] as $fieldName) {
567 if (isset($fields[$fieldName]) and $fields[$fieldName]['localizable']) {
568 $index['localizable'] = TRUE;
573 // check for unique index
574 if ($this->value('unique', $indexXML)) {
575 $index['unique'] = TRUE;
578 // field array cannot be empty
579 if (empty($index['field'])) {
580 echo "No fields defined for index $indexName\n";
584 // all fieldnames have to be defined and should exist in schema.
585 foreach ($index['field'] as $fieldName) {
587 echo "Invalid field defination for index $indexName\n";
590 $parenOffset = strpos($fieldName, '(');
591 if ($parenOffset > 0) {
592 $fieldName = substr($fieldName, 0, $parenOffset);
594 if (!array_key_exists($fieldName, $fields)) {
595 echo "Table does not contain $fieldName\n";
600 $indices[$indexName] = &$index;
606 * @param $foreignKeys
607 * @param string $currentTableName
609 public function getForeignKey(&$foreignXML, &$fields, &$foreignKeys, &$currentTableName) {
610 $name = trim((string ) $foreignXML->name
);
612 /** need to make sure there is a field of type name */
613 if (!array_key_exists($name, $fields)) {
614 echo "foreign $name in $currentTableName does not have a field definition, ignoring\n";
618 /** need to check for existence of table and key **/
619 $table = trim($this->value('table', $foreignXML));
623 'uniqName' => "FK_{$currentTableName}_{$name}",
624 'key' => trim($this->value('key', $foreignXML)),
625 'import' => $this->value('import', $foreignXML, FALSE),
626 'export' => $this->value('import', $foreignXML, FALSE),
627 // we do this matching in a separate phase (resolveForeignKeys)
629 'onDelete' => $this->value('onDelete', $foreignXML, FALSE),
631 $foreignKeys[$name] = &$foreignKey;
636 * @param $dynamicForeignKeys
638 public function getDynamicForeignKey(&$foreignXML, &$dynamicForeignKeys) {
640 'idColumn' => trim($foreignXML->idColumn
),
641 'typeColumn' => trim($foreignXML->typeColumn
),
642 'key' => trim($this->value('key', $foreignXML)),
644 $dynamicForeignKeys[] = $foreignKey;
650 * @param null $default
652 * @return null|string
654 protected function value($key, &$object, $default = NULL) {
655 if (isset($object->$key)) {
656 return (string ) $object->$key;
664 * @param string $name
668 protected function checkAndAppend(&$attributes, &$object, $name, $pre = NULL, $post = NULL) {
669 if (!isset($object->$name)) {
673 $value = $pre . trim($object->$name) . $post;
674 $this->append($attributes, ' ', trim($value));
682 protected function append(&$str, $delim, $name) {
687 if (is_array($name)) {
688 foreach ($name as $n) {
705 $str .= $delim . $name;
711 * Sets the size property of a textfield.
713 * @param string $fieldXML
715 * @return null|string
717 protected function getSize($fieldXML) {
718 // Extract from <size> tag if supplied
719 if (!empty($fieldXML->html
) && $this->value('size', $fieldXML->html
)) {
720 return $this->value('size', $fieldXML->html
);
722 // Infer from <length> tag if <size> was not explicitly set or was invalid
723 // This map is slightly different from CRM_Core_Form_Renderer::$_sizeMapper
724 // Because we usually want fields to render as smaller than their maxlength
734 foreach ($sizes as $length => $name) {
735 if ($fieldXML->length
<= $length) {
736 return "CRM_Utils_Type::$name";
739 return 'CRM_Utils_Type::HUGE';