CRM-14181, remove special handing for enums
[civicrm-core.git] / CRM / Core / CodeGen / Specification.php
CommitLineData
5e434adf
ARW
1<?php
2
3/**
4 * Read the schema specification and parse into internal data structures
5 */
6class CRM_Core_CodeGen_Specification {
7 public $tables;
8 public $database;
9
10 protected $classNames;
11
12 /**
13 * Read and parse.
14 *
15 * @param string $buildVersion which version of the schema to build
16 */
17 function parse($schemaPath, $buildVersion) {
18 $this->buildVersion = $buildVersion;
19
20 echo "Parsing schema description ".$schemaPath."\n";
21 $dbXML = CRM_Core_CodeGen_Util_Xml::parse($schemaPath);
22 // print_r( $dbXML );
23
24 echo "Extracting database information\n";
25 $this->database = &$this->getDatabase($dbXML);
26 // print_r( $this->database );
27
28 $this->classNames = array();
29
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);
33
34 $this->resolveForeignKeys($this->tables, $this->classNames);
35 $this->tables = $this->orderTables($this->tables);
36
37 // add archive tables here
38 $archiveTables = array( );
39 foreach ($this->tables as $name => $table ) {
40 if ( $table['archive'] == 'true' ) {
41 $name = 'archive_' . $table['name'];
42 $table['name'] = $name;
43 $table['archive'] = 'false';
44 if ( isset($table['foreignKey']) ) {
45 foreach ($table['foreignKey'] as $fkName => $fkValue) {
46 if ($this->tables[$fkValue['table']]['archive'] == 'true') {
47 $table['foreignKey'][$fkName]['table'] = 'archive_' . $table['foreignKey'][$fkName]['table'];
48 $table['foreignKey'][$fkName]['uniqName'] =
49 str_replace( 'FK_', 'FK_archive_', $table['foreignKey'][$fkName]['uniqName'] );
50 }
51 }
52 $archiveTables[$name] = $table;
53 }
54 }
55 }
56 }
57
58 function &getDatabase(&$dbXML) {
59 $database = array('name' => trim((string ) $dbXML->name));
60
61 $attributes = '';
62 $this->checkAndAppend($attributes, $dbXML, 'character_set', 'DEFAULT CHARACTER SET ', '');
63 $this->checkAndAppend($attributes, $dbXML, 'collate', 'COLLATE ', '');
64 $database['attributes'] = $attributes;
65
66 $tableAttributes_modern = $tableAttributes_simple = '';
67 $this->checkAndAppend($tableAttributes_modern, $dbXML, 'table_type', 'ENGINE=', '');
68 $this->checkAndAppend($tableAttributes_simple, $dbXML, 'table_type', 'TYPE=', '');
69 $database['tableAttributes_modern'] = trim($tableAttributes_modern . ' ' . $attributes);
70 $database['tableAttributes_simple'] = trim($tableAttributes_simple);
71
72 $database['comment'] = $this->value('comment', $dbXML, '');
73
74 return $database;
75 }
76
77 function getTables($dbXML, &$database) {
78 $tables = array();
79 foreach ($dbXML->tables as $tablesXML) {
80 foreach ($tablesXML->table as $tableXML) {
81 if ($this->value('drop', $tableXML, 0) > 0 and $this->value('drop', $tableXML, 0) <= $this->buildVersion) {
82 continue;
83 }
84
85 if ($this->value('add', $tableXML, 0) <= $this->buildVersion) {
86 $this->getTable($tableXML, $database, $tables);
87 }
88 }
89 }
90
91 return $tables;
92 }
93
94 function resolveForeignKeys(&$tables, &$classNames) {
95 foreach (array_keys($tables) as $name) {
96 $this->resolveForeignKey($tables, $classNames, $name);
97 }
98 }
99
100 function resolveForeignKey(&$tables, &$classNames, $name) {
101 if (!array_key_exists('foreignKey', $tables[$name])) {
102 return;
103 }
104
105 foreach (array_keys($tables[$name]['foreignKey']) as $fkey) {
106 $ftable = $tables[$name]['foreignKey'][$fkey]['table'];
107 if (!array_key_exists($ftable, $classNames)) {
108 echo "$ftable is not a valid foreign key table in $name\n";
109 continue;
110 }
111 $tables[$name]['foreignKey'][$fkey]['className'] = $classNames[$ftable];
112 $tables[$name]['foreignKey'][$fkey]['fileName'] = str_replace('_', '/', $classNames[$ftable]) . '.php';
113 $tables[$name]['fields'][$fkey]['FKClassName'] = $classNames[$ftable];
114 }
115 }
116
117 function orderTables(&$tables) {
118 $ordered = array();
119
120 while (!empty($tables)) {
121 foreach (array_keys($tables) as $name) {
122 if ($this->validTable($tables, $ordered, $name)) {
123 $ordered[$name] = $tables[$name];
124 unset($tables[$name]);
125 }
126 }
127 }
128 return $ordered;
129 }
130
131 function validTable(&$tables, &$valid, $name) {
132 if (!array_key_exists('foreignKey', $tables[$name])) {
133 return TRUE;
134 }
135
136 foreach (array_keys($tables[$name]['foreignKey']) as $fkey) {
137 $ftable = $tables[$name]['foreignKey'][$fkey]['table'];
138 if (!array_key_exists($ftable, $valid) && $ftable !== $name) {
139 return FALSE;
140 }
141 }
142 return TRUE;
143 }
144
145 function getTable($tableXML, &$database, &$tables) {
146 $name = trim((string ) $tableXML->name);
147 $klass = trim((string ) $tableXML->class);
148 $base = $this->value('base', $tableXML);
149 $sourceFile = "xml/schema/{$base}/{$klass}.xml";
150 $daoPath = "{$base}/DAO/";
151 $pre = str_replace('/', '_', $daoPath);
152 $this->classNames[$name] = $pre . $klass;
153
154 $localizable = FALSE;
155 foreach ($tableXML->field as $fieldXML) {
156 if ($fieldXML->localizable) {
157 $localizable = TRUE;
158 break;
159 }
160 }
161
162 $table = array(
163 'name' => $name,
164 'base' => $daoPath,
165 'sourceFile' => $sourceFile,
166 'fileName' => $klass . '.php',
167 'objectName' => $klass,
168 'labelName' => substr($name, 8),
169 'className' => $this->classNames[$name],
170 'attributes_simple' => trim($database['tableAttributes_simple']),
171 'attributes_modern' => trim($database['tableAttributes_modern']),
172 'comment' => $this->value('comment', $tableXML),
173 'localizable' => $localizable,
174 'log' => $this->value('log', $tableXML, 'false'),
175 'archive' => $this->value('archive', $tableXML, 'false'),
176 );
177
178 $fields = array();
179 foreach ($tableXML->field as $fieldXML) {
180 if ($this->value('drop', $fieldXML, 0) > 0 and $this->value('drop', $fieldXML, 0) <= $this->buildVersion) {
181 continue;
182 }
183
184 if ($this->value('add', $fieldXML, 0) <= $this->buildVersion) {
185 $this->getField($fieldXML, $fields);
186 }
187 }
188
189 $table['fields'] = &$fields;
5e434adf
ARW
190
191 if ($this->value('primaryKey', $tableXML)) {
192 $this->getPrimaryKey($tableXML->primaryKey, $fields, $table);
193 }
194
195 // some kind of refresh?
196 CRM_Core_Config::singleton(FALSE);
197 if ($this->value('index', $tableXML)) {
198 $index = array();
199 foreach ($tableXML->index as $indexXML) {
200 if ($this->value('drop', $indexXML, 0) > 0 and $this->value('drop', $indexXML, 0) <= $this->buildVersion) {
201 continue;
202 }
203
204 $this->getIndex($indexXML, $fields, $index);
205 }
206 $table['index'] = &$index;
207 }
208
209 if ($this->value('foreignKey', $tableXML)) {
210 $foreign = array();
211 foreach ($tableXML->foreignKey as $foreignXML) {
212 // print_r($foreignXML);
213
214 if ($this->value('drop', $foreignXML, 0) > 0 and $this->value('drop', $foreignXML, 0) <= $this->buildVersion) {
215 continue;
216 }
217 if ($this->value('add', $foreignXML, 0) <= $this->buildVersion) {
218 $this->getForeignKey($foreignXML, $fields, $foreign, $name);
219 }
220 }
221 $table['foreignKey'] = &$foreign;
222 }
223
224 if ($this->value('dynamicForeignKey', $tableXML)) {
225 $dynamicForeign = array();
226 foreach ($tableXML->dynamicForeignKey as $foreignXML) {
227 if ($this->value('drop', $foreignXML, 0) > 0 and $this->value('drop', $foreignXML, 0) <= $this->buildVersion) {
228 continue;
229 }
230 if ($this->value('add', $foreignXML, 0) <= $this->buildVersion) {
231 $this->getDynamicForeignKey($foreignXML, $dynamicForeign, $name);
232 }
233 }
234 $table['dynamicForeignKey'] = $dynamicForeign;
235 }
236
237 $tables[$name] = &$table;
238 return;
239 }
240
241 function getField(&$fieldXML, &$fields) {
242 $name = trim((string ) $fieldXML->name);
243 $field = array('name' => $name, 'localizable' => $fieldXML->localizable);
244 $type = (string ) $fieldXML->type;
245 switch ($type) {
246 case 'varchar':
247 case 'char':
248 $field['length'] = (int) $fieldXML->length;
249 $field['sqlType'] = "$type({$field['length']})";
250 $field['phpType'] = 'string';
251 $field['crmType'] = 'CRM_Utils_Type::T_STRING';
252 $field['size'] = $this->getSize($fieldXML);
253 break;
254
5e434adf
ARW
255 case 'text':
256 $field['sqlType'] = $field['phpType'] = $type;
257 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
5e545f38
CW
258 // CRM-13497 see fixme below
259 $field['rows'] = isset($fieldXML->html) ? $this->value('rows', $fieldXML->html) : NULL;
260 $field['cols'] = isset($fieldXML->html) ? $this->value('cols', $fieldXML->html) : NULL;
261 break;
5e434adf
ARW
262 break;
263
264 case 'datetime':
265 $field['sqlType'] = $field['phpType'] = $type;
266 $field['crmType'] = 'CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME';
267 break;
268
269 case 'boolean':
270 // need this case since some versions of mysql do not have boolean as a valid column type and hence it
271 // is changed to tinyint. hopefully after 2 yrs this case can be removed.
272 $field['sqlType'] = 'tinyint';
273 $field['phpType'] = $type;
274 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
275 break;
276
277 case 'decimal':
278 $length = $fieldXML->length ? $fieldXML->length : '20,2';
279 $field['sqlType'] = 'decimal(' . $length . ')';
280 $field['phpType'] = 'float';
281 $field['crmType'] = 'CRM_Utils_Type::T_MONEY';
282 break;
283
284 case 'float':
285 $field['sqlType'] = 'double';
286 $field['phpType'] = 'float';
287 $field['crmType'] = 'CRM_Utils_Type::T_FLOAT';
288 break;
289
290 default:
291 $field['sqlType'] = $field['phpType'] = $type;
292 if ($type == 'int unsigned') {
293 $field['crmType'] = 'CRM_Utils_Type::T_INT';
294 }
295 else {
296 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
297 }
298 break;
299 }
300
301 $field['required'] = $this->value('required', $fieldXML);
302 $field['collate'] = $this->value('collate', $fieldXML);
303 $field['comment'] = $this->value('comment', $fieldXML);
304 $field['default'] = $this->value('default', $fieldXML);
305 $field['import'] = $this->value('import', $fieldXML);
306 if ($this->value('export', $fieldXML)) {
307 $field['export'] = $this->value('export', $fieldXML);
308 }
309 else {
310 $field['export'] = $this->value('import', $fieldXML);
311 }
312 $field['rule'] = $this->value('rule', $fieldXML);
313 $field['title'] = $this->value('title', $fieldXML);
314 if (!$field['title']) {
315 $field['title'] = $this->composeTitle($name);
316 }
317 $field['headerPattern'] = $this->value('headerPattern', $fieldXML);
318 $field['dataPattern'] = $this->value('dataPattern', $fieldXML);
319 $field['uniqueName'] = $this->value('uniqueName', $fieldXML);
5e545f38
CW
320 $field['html'] = $this->value('html', $fieldXML);
321 if (!empty($field['html'])) {
322 $validOptions = array(
323 'type',
324 /* Fixme: prior to CRM-13497 these were in a flat structure
325 // CRM-13497 moved them to be nested within 'html' but there's no point
326 // making that change in the DAOs right now since we are in the process of
327 // moving to docrtine anyway.
328 // So translating from nested xml back to flat structure for now.
329 'rows',
330 'cols',
331 'size', */
332 );
333 $field['html'] = array();
334 foreach ($validOptions as $htmlOption) {
335 if(!empty($fieldXML->html->$htmlOption)){
336 $field['html'][$htmlOption] = $this->value($htmlOption, $fieldXML->html);
337 }
338 }
339 }
5e434adf
ARW
340 $field['pseudoconstant'] = $this->value('pseudoconstant', $fieldXML);
341 if(!empty($field['pseudoconstant'])){
342 //ok this is a bit long-winded but it gets there & is consistent with above approach
343 $field['pseudoconstant'] = array();
344 $validOptions = array(
345 // Fields can specify EITHER optionGroupName OR table, not both
346 // (since declaring optionGroupName means we are using the civicrm_option_value table)
347 'optionGroupName',
348 'table',
349 // If table is specified, keyColumn and labelColumn are also required
350 'keyColumn',
351 'labelColumn',
352 // Non-translated machine name for programmatic lookup. Defaults to 'name' if that column exists
353 'nameColumn',
354 // Where clause snippet (will be joined to the rest of the query with AND operator)
355 'condition',
356 );
357 foreach ($validOptions as $pseudoOption) {
358 if(!empty($fieldXML->pseudoconstant->$pseudoOption)){
359 $field['pseudoconstant'][$pseudoOption] = $this->value($pseudoOption, $fieldXML->pseudoconstant);
360 }
361 }
362 // For now, fields that have option lists that are not in the db can simply
363 // declare an empty pseudoconstant tag and we'll add this placeholder.
364 // That field's BAO::buildOptions fn will need to be responsible for generating the option list
365 if (empty($field['pseudoconstant'])) {
366 $field['pseudoconstant'] = 'not in database';
367 }
368 }
369 $fields[$name] = &$field;
370 }
371
372 function composeTitle($name) {
373 $names = explode('_', strtolower($name));
374 $title = '';
375 for ($i = 0; $i < count($names); $i++) {
376 if ($names[$i] === 'id' || $names[$i] === 'is') {
377 // id's do not get titles
378 return NULL;
379 }
380
381 if ($names[$i] === 'im') {
382 $names[$i] = 'IM';
383 }
384 else {
385 $names[$i] = ucfirst(trim($names[$i]));
386 }
387
388 $title = $title . ' ' . $names[$i];
389 }
390 return trim($title);
391 }
392
393 function getPrimaryKey(&$primaryXML, &$fields, &$table) {
394 $name = trim((string ) $primaryXML->name);
395
396 /** need to make sure there is a field of type name */
397 if (!array_key_exists($name, $fields)) {
398 echo "primary key $name in $table->name does not have a field definition, ignoring\n";
399 return;
400 }
401
402 // set the autoincrement property of the field
403 $auto = $this->value('autoincrement', $primaryXML);
404 $fields[$name]['autoincrement'] = $auto;
405 $primaryKey = array(
406 'name' => $name,
407 'autoincrement' => $auto,
408 );
409 $table['primaryKey'] = &$primaryKey;
410 }
411
412 function getIndex(&$indexXML, &$fields, &$indices) {
413 //echo "\n\n*******************************************************\n";
414 //echo "entering getIndex\n";
415
416 $index = array();
417 // empty index name is fine
418 $indexName = trim((string)$indexXML->name);
419 $index['name'] = $indexName;
420 $index['field'] = array();
421
422 // populate fields
423 foreach ($indexXML->fieldName as $v) {
424 $fieldName = (string)($v);
425 $length = (string)($v['length']);
426 if (strlen($length) > 0) {
427 $fieldName = "$fieldName($length)";
428 }
429 $index['field'][] = $fieldName;
430 }
431
432 $index['localizable'] = FALSE;
433 foreach ($index['field'] as $fieldName) {
434 if (isset($fields[$fieldName]) and $fields[$fieldName]['localizable']) {
435 $index['localizable'] = TRUE;
436 break;
437 }
438 }
439
440 // check for unique index
441 if ($this->value('unique', $indexXML)) {
442 $index['unique'] = TRUE;
443 }
444
445 //echo "\$index = \n";
446 //print_r($index);
447
448 // field array cannot be empty
449 if (empty($index['field'])) {
450 echo "No fields defined for index $indexName\n";
451 return;
452 }
453
454 // all fieldnames have to be defined and should exist in schema.
455 foreach ($index['field'] as $fieldName) {
456 if (!$fieldName) {
457 echo "Invalid field defination for index $indexName\n";
458 return;
459 }
460 $parenOffset = strpos($fieldName, '(');
461 if ($parenOffset > 0) {
462 $fieldName = substr($fieldName, 0, $parenOffset);
463 }
464 if (!array_key_exists($fieldName, $fields)) {
465 echo "Table does not contain $fieldName\n";
466 print_r($fields);
467 exit();
468 }
469 }
470 $indices[$indexName] = &$index;
471 }
472
473 function getForeignKey(&$foreignXML, &$fields, &$foreignKeys, &$currentTableName) {
474 $name = trim((string ) $foreignXML->name);
475
476 /** need to make sure there is a field of type name */
477 if (!array_key_exists($name, $fields)) {
478 echo "foreign $name in $currentTableName does not have a field definition, ignoring\n";
479 return;
480 }
481
482 /** need to check for existence of table and key **/
483 $table = trim($this->value('table', $foreignXML));
484 $foreignKey = array(
485 'name' => $name,
486 'table' => $table,
487 'uniqName' => "FK_{$currentTableName}_{$name}",
488 'key' => trim($this->value('key', $foreignXML)),
489 'import' => $this->value('import', $foreignXML, FALSE),
490 'export' => $this->value('import', $foreignXML, FALSE),
491 // we do this matching in a seperate phase (resolveForeignKeys)
492 'className' => NULL,
493 'onDelete' => $this->value('onDelete', $foreignXML, FALSE),
494 );
495 $foreignKeys[$name] = &$foreignKey;
496 }
497
498 function getDynamicForeignKey(&$foreignXML, &$dynamicForeignKeys) {
499 $foreignKey = array(
500 'idColumn' => trim($foreignXML->idColumn),
501 'typeColumn' => trim($foreignXML->typeColumn),
502 'key' => trim($this->value('key', $foreignXML)),
503 );
504 $dynamicForeignKeys[] = $foreignKey;
505 }
506
507 protected function value($key, &$object, $default = NULL) {
508 if (isset($object->$key)) {
509 return (string ) $object->$key;
510 }
511 return $default;
512 }
513
514 protected function checkAndAppend(&$attributes, &$object, $name, $pre = NULL, $post = NULL) {
515 if (!isset($object->$name)) {
516 return;
517 }
518
519 $value = $pre . trim($object->$name) . $post;
520 $this->append($attributes, ' ', trim($value));
521 }
522
523 protected function append(&$str, $delim, $name) {
524 if (empty($name)) {
525 return;
526 }
527
528 if (is_array($name)) {
529 foreach ($name as $n) {
530 if (empty($n)) {
531 continue;
532 }
533 if (empty($str)) {
534 $str = $n;
535 }
536 else {
537 $str .= $delim . $n;
538 }
539 }
540 }
541 else {
542 if (empty($str)) {
543 $str = $name;
544 }
545 else {
546 $str .= $delim . $name;
547 }
548 }
549 }
550
551 /**
552 * Sets the size property of a textfield
553 * See constants defined in CRM_Utils_Type for possible values
554 */
555 protected function getSize($fieldXML) {
556 // Extract from <size> tag if supplied
5e545f38
CW
557 if (!empty($fieldXML->html) && $this->value('size', $fieldXML->html)) {
558 $const = 'CRM_Utils_Type::' . strtoupper($fieldXML->html->size);
5e434adf
ARW
559 if (defined($const)) {
560 return $const;
561 }
562 }
563 // Infer from <length> tag if <size> was not explicitly set or was invalid
564
565 // This map is slightly different from CRM_Core_Form_Renderer::$_sizeMapper
566 // Because we usually want fields to render as smaller than their maxlength
567 $sizes = array(
568 2 => 'TWO',
569 4 => 'FOUR',
570 6 => 'SIX',
571 8 => 'EIGHT',
572 16 => 'TWELVE',
573 32 => 'MEDIUM',
574 64 => 'BIG',
575 );
576 foreach ($sizes as $length => $name) {
577 if ($fieldXML->length <= $length) {
578 return "CRM_Utils_Type::$name";
579 }
580 }
581 return 'CRM_Utils_Type::HUGE';
582 }
583}