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['serialize'] = $this->value('serialize', $fieldXML);
365 $field['html'] = $this->value('html', $fieldXML);
366 if (!empty($field['html'])) {
367 $validOptions = array(
370 /* Fixme: prior to CRM-13497 these were in a flat structure
371 // CRM-13497 moved them to be nested within 'html' but there's no point
372 // making that change in the DAOs right now since we are in the process of
373 // moving to docrtine anyway.
374 // So translating from nested xml back to flat structure for now.
379 $field['html'] = array();
380 foreach ($validOptions as $htmlOption) {
381 if (!empty($fieldXML->html
->$htmlOption)) {
382 $field['html'][$htmlOption] = $this->value($htmlOption, $fieldXML->html
);
387 // in multilingual context popup, we need extra information to create appropriate widget
388 if ($fieldXML->localizable
) {
389 if (isset($fieldXML->html
)) {
390 $field['widget'] = (array) $fieldXML->html
;
394 $field['widget'] = array('type' => 'Text');
396 if (isset($fieldXML->required
)) {
397 $field['widget']['required'] = $this->value('required', $fieldXML);
401 $field['pseudoconstant'] = $this->value('pseudoconstant', $fieldXML);
402 if (!empty($field['pseudoconstant'])) {
403 //ok this is a bit long-winded but it gets there & is consistent with above approach
404 $field['pseudoconstant'] = array();
405 $validOptions = array(
406 // Fields can specify EITHER optionGroupName OR table, not both
407 // (since declaring optionGroupName means we are using the civicrm_option_value table)
410 // If table is specified, keyColumn and labelColumn are also required
413 // Non-translated machine name for programmatic lookup. Defaults to 'name' if that column exists
415 // Where clause snippet (will be joined to the rest of the query with AND operator)
417 // callback function incase of static arrays
419 // Path to options edit form
422 foreach ($validOptions as $pseudoOption) {
423 if (!empty($fieldXML->pseudoconstant
->$pseudoOption)) {
424 $field['pseudoconstant'][$pseudoOption] = $this->value($pseudoOption, $fieldXML->pseudoconstant
);
427 if (!isset($field['pseudoconstant']['optionEditPath']) && !empty($field['pseudoconstant']['optionGroupName'])) {
428 $field['pseudoconstant']['optionEditPath'] = 'civicrm/admin/options/' . $field['pseudoconstant']['optionGroupName'];
430 // For now, fields that have option lists that are not in the db can simply
431 // declare an empty pseudoconstant tag and we'll add this placeholder.
432 // That field's BAO::buildOptions fn will need to be responsible for generating the option list
433 if (empty($field['pseudoconstant'])) {
434 $field['pseudoconstant'] = 'not in database';
437 $fields[$name] = &$field;
441 * @param string $name
445 public function composeTitle($name) {
446 $names = explode('_', strtolower($name));
448 for ($i = 0; $i < count($names); $i++
) {
449 if ($names[$i] === 'id' ||
$names[$i] === 'is') {
450 // id's do not get titles
454 if ($names[$i] === 'im') {
458 $names[$i] = ucfirst(trim($names[$i]));
461 $title = $title . ' ' . $names[$i];
467 * @param object $primaryXML
468 * @param array $fields
469 * @param array $table
471 public function getPrimaryKey(&$primaryXML, &$fields, &$table) {
472 $name = trim((string ) $primaryXML->name
);
474 // set the autoincrement property of the field
475 $auto = $this->value('autoincrement', $primaryXML);
476 if (isset($fields[$name])) {
477 $fields[$name]['autoincrement'] = $auto;
479 $fields[$name]['autoincrement'] = $auto;
482 'autoincrement' => $auto,
486 foreach ($primaryXML->fieldName
as $v) {
487 $fieldName = (string) ($v);
488 $length = (string) ($v['length']);
489 if (strlen($length) > 0) {
490 $fieldName = "$fieldName($length)";
492 $primaryKey['field'][] = $fieldName;
495 // when field array is empty set it to the name of the primary key.
496 if (empty($primaryKey['field'])) {
497 $primaryKey['field'][] = $name;
500 // all fieldnames have to be defined and should exist in schema.
501 foreach ($primaryKey['field'] as $fieldName) {
503 echo "Invalid field defination for index $name\n";
506 $parenOffset = strpos($fieldName, '(');
507 if ($parenOffset > 0) {
508 $fieldName = substr($fieldName, 0, $parenOffset);
510 if (!array_key_exists($fieldName, $fields)) {
511 echo "Table does not contain $fieldName\n";
517 $table['primaryKey'] = &$primaryKey;
525 public function getIndex(&$indexXML, &$fields, &$indices) {
526 //echo "\n\n*******************************************************\n";
527 //echo "entering getIndex\n";
530 // empty index name is fine
531 $indexName = trim((string) $indexXML->name
);
532 $index['name'] = $indexName;
533 $index['field'] = array();
536 foreach ($indexXML->fieldName
as $v) {
537 $fieldName = (string) ($v);
538 $length = (string) ($v['length']);
539 if (strlen($length) > 0) {
540 $fieldName = "$fieldName($length)";
542 $index['field'][] = $fieldName;
545 $index['localizable'] = FALSE;
546 foreach ($index['field'] as $fieldName) {
547 if (isset($fields[$fieldName]) and $fields[$fieldName]['localizable']) {
548 $index['localizable'] = TRUE;
553 // check for unique index
554 if ($this->value('unique', $indexXML)) {
555 $index['unique'] = TRUE;
558 // field array cannot be empty
559 if (empty($index['field'])) {
560 echo "No fields defined for index $indexName\n";
564 // all fieldnames have to be defined and should exist in schema.
565 foreach ($index['field'] as $fieldName) {
567 echo "Invalid field defination for index $indexName\n";
570 $parenOffset = strpos($fieldName, '(');
571 if ($parenOffset > 0) {
572 $fieldName = substr($fieldName, 0, $parenOffset);
574 if (!array_key_exists($fieldName, $fields)) {
575 echo "Table does not contain $fieldName\n";
580 $indices[$indexName] = &$index;
586 * @param $foreignKeys
587 * @param string $currentTableName
589 public function getForeignKey(&$foreignXML, &$fields, &$foreignKeys, &$currentTableName) {
590 $name = trim((string ) $foreignXML->name
);
592 /** need to make sure there is a field of type name */
593 if (!array_key_exists($name, $fields)) {
594 echo "foreign $name in $currentTableName does not have a field definition, ignoring\n";
598 /** need to check for existence of table and key **/
599 $table = trim($this->value('table', $foreignXML));
603 'uniqName' => "FK_{$currentTableName}_{$name}",
604 'key' => trim($this->value('key', $foreignXML)),
605 'import' => $this->value('import', $foreignXML, FALSE),
606 'export' => $this->value('import', $foreignXML, FALSE),
607 // we do this matching in a separate phase (resolveForeignKeys)
609 'onDelete' => $this->value('onDelete', $foreignXML, FALSE),
611 $foreignKeys[$name] = &$foreignKey;
616 * @param $dynamicForeignKeys
618 public function getDynamicForeignKey(&$foreignXML, &$dynamicForeignKeys) {
620 'idColumn' => trim($foreignXML->idColumn
),
621 'typeColumn' => trim($foreignXML->typeColumn
),
622 'key' => trim($this->value('key', $foreignXML)),
624 $dynamicForeignKeys[] = $foreignKey;
630 * @param null $default
632 * @return null|string
634 protected function value($key, &$object, $default = NULL) {
635 if (isset($object->$key)) {
636 return (string ) $object->$key;
644 * @param string $name
648 protected function checkAndAppend(&$attributes, &$object, $name, $pre = NULL, $post = NULL) {
649 if (!isset($object->$name)) {
653 $value = $pre . trim($object->$name) . $post;
654 $this->append($attributes, ' ', trim($value));
662 protected function append(&$str, $delim, $name) {
667 if (is_array($name)) {
668 foreach ($name as $n) {
685 $str .= $delim . $name;
691 * Sets the size property of a textfield.
693 * @param string $fieldXML
695 * @return null|string
697 protected function getSize($fieldXML) {
698 // Extract from <size> tag if supplied
699 if (!empty($fieldXML->html
) && $this->value('size', $fieldXML->html
)) {
700 return $this->value('size', $fieldXML->html
);
702 // Infer from <length> tag if <size> was not explicitly set or was invalid
703 // This map is slightly different from CRM_Core_Form_Renderer::$_sizeMapper
704 // Because we usually want fields to render as smaller than their maxlength
714 foreach ($sizes as $length => $name) {
715 if ($fieldXML->length
<= $length) {
716 return "CRM_Utils_Type::$name";
719 return 'CRM_Utils_Type::HUGE';