Merge pull request #18148 from civicrm/5.29
[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 *
77b97be7 15 * @param $schemaPath
6a0b768e
TO
16 * @param string $buildVersion
17 * Which version of the schema to build.
518fa0ee 18 * @param bool $verbose
5e434adf 19 */
644ba48e 20 public function parse($schemaPath, $buildVersion, $verbose = TRUE) {
5e434adf
ARW
21 $this->buildVersion = $buildVersion;
22
644ba48e
TO
23 if ($verbose) {
24 echo "Parsing schema description " . $schemaPath . "\n";
25 }
5e434adf 26 $dbXML = CRM_Core_CodeGen_Util_Xml::parse($schemaPath);
5e434adf 27
644ba48e
TO
28 if ($verbose) {
29 echo "Extracting database information\n";
30 }
5e434adf 31 $this->database = &$this->getDatabase($dbXML);
5e434adf 32
be2fb01f 33 $this->classNames = [];
5e434adf 34
041ecc95 35 // TODO: peel DAO-specific stuff out of getTables, and spec reading into its own class
644ba48e
TO
36 if ($verbose) {
37 echo "Extracting table information\n";
38 }
5e434adf
ARW
39 $this->tables = $this->getTables($dbXML, $this->database);
40
41 $this->resolveForeignKeys($this->tables, $this->classNames);
42 $this->tables = $this->orderTables($this->tables);
43
44 // add archive tables here
481a74f4
TO
45 foreach ($this->tables as $name => $table) {
46 if ($table['archive'] == 'true') {
5e434adf
ARW
47 $name = 'archive_' . $table['name'];
48 $table['name'] = $name;
49 $table['archive'] = 'false';
481a74f4 50 if (isset($table['foreignKey'])) {
5e434adf
ARW
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'];
acb1052e
WA
54 $table['foreignKey'][$fkName]['uniqName']
55 = str_replace('FK_', 'FK_archive_', $table['foreignKey'][$fkName]['uniqName']);
5e434adf
ARW
56 }
57 }
58 $archiveTables[$name] = $table;
59 }
60 }
61 }
62 }
63
2558c2b0
EM
64 /**
65 * @param $dbXML
66 *
67 * @return array
68 */
00be9182 69 public function &getDatabase(&$dbXML) {
be2fb01f 70 $database = ['name' => trim((string ) $dbXML->name)];
5e434adf
ARW
71
72 $attributes = '';
73 $this->checkAndAppend($attributes, $dbXML, 'character_set', 'DEFAULT CHARACTER SET ', '');
74 $this->checkAndAppend($attributes, $dbXML, 'collate', 'COLLATE ', '');
75 $database['attributes'] = $attributes;
76
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);
82
83 $database['comment'] = $this->value('comment', $dbXML, '');
84
85 return $database;
86 }
87
2558c2b0
EM
88 /**
89 * @param $dbXML
90 * @param $database
91 *
92 * @return array
93 */
00be9182 94 public function getTables($dbXML, &$database) {
be2fb01f 95 $tables = [];
5e434adf
ARW
96 foreach ($dbXML->tables as $tablesXML) {
97 foreach ($tablesXML->table as $tableXML) {
eb59d669 98 if ($this->value('drop', $tableXML, 0) > 0 && version_compare($this->value('drop', $tableXML, 0), $this->buildVersion, '<=')) {
5e434adf
ARW
99 continue;
100 }
101
eb59d669 102 if (version_compare($this->value('add', $tableXML, 0), $this->buildVersion, '<=')) {
5e434adf
ARW
103 $this->getTable($tableXML, $database, $tables);
104 }
105 }
106 }
107
108 return $tables;
109 }
110
2558c2b0
EM
111 /**
112 * @param $tables
100fef9d 113 * @param string $classNames
2558c2b0 114 */
00be9182 115 public function resolveForeignKeys(&$tables, &$classNames) {
5e434adf
ARW
116 foreach (array_keys($tables) as $name) {
117 $this->resolveForeignKey($tables, $classNames, $name);
118 }
119 }
120
2558c2b0
EM
121 /**
122 * @param $tables
100fef9d
CW
123 * @param string $classNames
124 * @param string $name
2558c2b0 125 */
00be9182 126 public function resolveForeignKey(&$tables, &$classNames, $name) {
5e434adf
ARW
127 if (!array_key_exists('foreignKey', $tables[$name])) {
128 return;
129 }
130
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";
135 continue;
136 }
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];
140 }
141 }
142
2558c2b0
EM
143 /**
144 * @param $tables
145 *
146 * @return array
147 */
00be9182 148 public function orderTables(&$tables) {
be2fb01f 149 $ordered = [];
5e434adf
ARW
150
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]);
156 }
157 }
158 }
159 return $ordered;
160 }
161
2558c2b0
EM
162 /**
163 * @param $tables
100fef9d
CW
164 * @param int $valid
165 * @param string $name
2558c2b0
EM
166 *
167 * @return bool
168 */
00be9182 169 public function validTable(&$tables, &$valid, $name) {
5e434adf
ARW
170 if (!array_key_exists('foreignKey', $tables[$name])) {
171 return TRUE;
172 }
173
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) {
177 return FALSE;
178 }
179 }
180 return TRUE;
181 }
182
2558c2b0
EM
183 /**
184 * @param $tableXML
185 * @param $database
186 * @param $tables
187 */
00be9182 188 public function getTable($tableXML, &$database, &$tables) {
5e434adf
ARW
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/";
3cef3c00 194 $baoPath = __DIR__ . '/../../../' . str_replace(' ', '', "{$base}/BAO/");
915274c8 195 $useBao = $this->value('useBao', $tableXML, file_exists($baoPath . $klass . '.php'));
5e434adf
ARW
196 $pre = str_replace('/', '_', $daoPath);
197 $this->classNames[$name] = $pre . $klass;
198
199 $localizable = FALSE;
200 foreach ($tableXML->field as $fieldXML) {
201 if ($fieldXML->localizable) {
202 $localizable = TRUE;
203 break;
204 }
205 }
206
be2fb01f 207 $table = [
5e434adf
ARW
208 'name' => $name,
209 'base' => $daoPath,
210 'sourceFile' => $sourceFile,
211 'fileName' => $klass . '.php',
212 'objectName' => $klass,
449c4e6b
CW
213 'title' => $tableXML->title ?? self::nameToTitle($klass),
214 'icon' => $tableXML->icon ?? NULL,
4b4cf875 215 'add' => $tableXML->add ?? NULL,
5e434adf
ARW
216 'labelName' => substr($name, 8),
217 'className' => $this->classNames[$name],
915274c8 218 'bao' => ($useBao ? str_replace('DAO', 'BAO', $this->classNames[$name]) : $this->classNames[$name]),
3cef3c00 219 'entity' => $klass,
5e434adf
ARW
220 'attributes_simple' => trim($database['tableAttributes_simple']),
221 'attributes_modern' => trim($database['tableAttributes_modern']),
222 'comment' => $this->value('comment', $tableXML),
223 'localizable' => $localizable,
224 'log' => $this->value('log', $tableXML, 'false'),
225 'archive' => $this->value('archive', $tableXML, 'false'),
be2fb01f 226 ];
5e434adf 227
be2fb01f 228 $fields = [];
5e434adf 229 foreach ($tableXML->field as $fieldXML) {
eb59d669 230 if ($this->value('drop', $fieldXML, 0) > 0 && version_compare($this->value('drop', $fieldXML, 0), $this->buildVersion, '<=')) {
5e434adf
ARW
231 continue;
232 }
233
eb59d669 234 if (version_compare($this->value('add', $fieldXML, 0), $this->buildVersion, '<=')) {
5e434adf
ARW
235 $this->getField($fieldXML, $fields);
236 }
237 }
238
239 $table['fields'] = &$fields;
5e434adf
ARW
240
241 if ($this->value('primaryKey', $tableXML)) {
242 $this->getPrimaryKey($tableXML->primaryKey, $fields, $table);
243 }
244
5e434adf 245 if ($this->value('index', $tableXML)) {
be2fb01f 246 $index = [];
5e434adf 247 foreach ($tableXML->index as $indexXML) {
eb59d669 248 if ($this->value('drop', $indexXML, 0) > 0 && version_compare($this->value('drop', $indexXML, 0), $this->buildVersion, '<=')) {
5e434adf
ARW
249 continue;
250 }
251
252 $this->getIndex($indexXML, $fields, $index);
253 }
6b86d84f 254 CRM_Core_BAO_SchemaHandler::addIndexSignature($name, $index);
5e434adf
ARW
255 $table['index'] = &$index;
256 }
257
258 if ($this->value('foreignKey', $tableXML)) {
be2fb01f 259 $foreign = [];
5e434adf 260 foreach ($tableXML->foreignKey as $foreignXML) {
5e434adf 261
eb59d669 262 if ($this->value('drop', $foreignXML, 0) > 0 && version_compare($this->value('drop', $foreignXML, 0), $this->buildVersion, '<=')) {
5e434adf
ARW
263 continue;
264 }
eb59d669 265 if (version_compare($this->value('add', $foreignXML, 0), $this->buildVersion, '<=')) {
5e434adf
ARW
266 $this->getForeignKey($foreignXML, $fields, $foreign, $name);
267 }
268 }
269 $table['foreignKey'] = &$foreign;
270 }
271
272 if ($this->value('dynamicForeignKey', $tableXML)) {
be2fb01f 273 $dynamicForeign = [];
5e434adf 274 foreach ($tableXML->dynamicForeignKey as $foreignXML) {
eb59d669 275 if ($this->value('drop', $foreignXML, 0) > 0 && version_compare($this->value('drop', $foreignXML, 0), $this->buildVersion, '<=')) {
5e434adf
ARW
276 continue;
277 }
eb59d669 278 if (version_compare($this->value('add', $foreignXML, 0), $this->buildVersion, '<=')) {
5e434adf
ARW
279 $this->getDynamicForeignKey($foreignXML, $dynamicForeign, $name);
280 }
281 }
282 $table['dynamicForeignKey'] = $dynamicForeign;
283 }
284
285 $tables[$name] = &$table;
5e434adf
ARW
286 }
287
2558c2b0
EM
288 /**
289 * @param $fieldXML
290 * @param $fields
291 */
00be9182 292 public function getField(&$fieldXML, &$fields) {
353ffa53 293 $name = trim((string ) $fieldXML->name);
be2fb01f 294 $field = ['name' => $name, 'localizable' => ((bool) $fieldXML->localizable) ? 1 : 0];
353ffa53 295 $type = (string ) $fieldXML->type;
5e434adf
ARW
296 switch ($type) {
297 case 'varchar':
298 case 'char':
299 $field['length'] = (int) $fieldXML->length;
300 $field['sqlType'] = "$type({$field['length']})";
301 $field['phpType'] = 'string';
302 $field['crmType'] = 'CRM_Utils_Type::T_STRING';
303 $field['size'] = $this->getSize($fieldXML);
304 break;
305
5e434adf
ARW
306 case 'text':
307 $field['sqlType'] = $field['phpType'] = $type;
308 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
5e545f38
CW
309 // CRM-13497 see fixme below
310 $field['rows'] = isset($fieldXML->html) ? $this->value('rows', $fieldXML->html) : NULL;
311 $field['cols'] = isset($fieldXML->html) ? $this->value('cols', $fieldXML->html) : NULL;
312 break;
2aa397bc 313
acb1052e 314 break;
5e434adf
ARW
315
316 case 'datetime':
317 $field['sqlType'] = $field['phpType'] = $type;
318 $field['crmType'] = 'CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME';
319 break;
320
321 case 'boolean':
322 // need this case since some versions of mysql do not have boolean as a valid column type and hence it
323 // is changed to tinyint. hopefully after 2 yrs this case can be removed.
324 $field['sqlType'] = 'tinyint';
a296e35e 325 $field['phpType'] = 'bool';
5e434adf
ARW
326 $field['crmType'] = 'CRM_Utils_Type::T_' . strtoupper($type);
327 break;
328
329 case 'decimal':
330 $length = $fieldXML->length ? $fieldXML->length : '20,2';
331 $field['sqlType'] = 'decimal(' . $length . ')';
332 $field['phpType'] = 'float';
333 $field['crmType'] = 'CRM_Utils_Type::T_MONEY';
fb607354 334 $field['precision'] = $length . ',';
5e434adf
ARW
335 break;
336
337 case 'float':
338 $field['sqlType'] = 'double';
339 $field['phpType'] = 'float';
340 $field['crmType'] = 'CRM_Utils_Type::T_FLOAT';
341 break;
342
343 default:
3ab3ff17
SL
344 $field['phpType'] = $this->value('phpType', $fieldXML, $type);
345 $field['sqlType'] = $type;
e0674c37 346 if ($type == 'int unsigned' || $type == 'tinyint') {
a296e35e 347 $field['phpType'] = 'int';
5e434adf
ARW
348 $field['crmType'] = 'CRM_Utils_Type::T_INT';
349 }
350 else {
3ab3ff17 351 $field['crmType'] = $this->value('crmType', $fieldXML, 'CRM_Utils_Type::T_' . strtoupper($type));
5e434adf
ARW
352 }
353 break;
354 }
355
356 $field['required'] = $this->value('required', $fieldXML);
353ffa53
TO
357 $field['collate'] = $this->value('collate', $fieldXML);
358 $field['comment'] = $this->value('comment', $fieldXML);
359 $field['default'] = $this->value('default', $fieldXML);
360 $field['import'] = $this->value('import', $fieldXML);
5e434adf
ARW
361 if ($this->value('export', $fieldXML)) {
362 $field['export'] = $this->value('export', $fieldXML);
363 }
364 else {
365 $field['export'] = $this->value('import', $fieldXML);
366 }
367 $field['rule'] = $this->value('rule', $fieldXML);
368 $field['title'] = $this->value('title', $fieldXML);
369 if (!$field['title']) {
370 $field['title'] = $this->composeTitle($name);
371 }
372 $field['headerPattern'] = $this->value('headerPattern', $fieldXML);
373 $field['dataPattern'] = $this->value('dataPattern', $fieldXML);
374 $field['uniqueName'] = $this->value('uniqueName', $fieldXML);
74db51d3 375 $field['uniqueTitle'] = $this->value('uniqueTitle', $fieldXML);
2a5c9b4d 376 $field['serialize'] = $this->value('serialize', $fieldXML);
5e545f38 377 $field['html'] = $this->value('html', $fieldXML);
f5c0f096 378 $field['contactType'] = $this->value('contactType', $fieldXML);
1713a0ec
CW
379 if (isset($fieldXML->permission)) {
380 $field['permission'] = trim($this->value('permission', $fieldXML));
381 $field['permission'] = $field['permission'] ? array_filter(array_map('trim', explode(',', $field['permission']))) : [];
382 if (isset($fieldXML->permission->or)) {
383 $field['permission'][] = array_filter(array_map('trim', explode(',', $fieldXML->permission->or)));
384 }
385 }
5e545f38 386 if (!empty($field['html'])) {
be2fb01f 387 $validOptions = [
5e545f38 388 'type',
24317d89 389 'formatType',
80a96508 390 'label',
8ada2bfd 391 'controlField',
5e545f38
CW
392 /* Fixme: prior to CRM-13497 these were in a flat structure
393 // CRM-13497 moved them to be nested within 'html' but there's no point
394 // making that change in the DAOs right now since we are in the process of
395 // moving to docrtine anyway.
396 // So translating from nested xml back to flat structure for now.
397 'rows',
398 'cols',
399 'size', */
be2fb01f
CW
400 ];
401 $field['html'] = [];
5e545f38 402 foreach ($validOptions as $htmlOption) {
9b873358 403 if (!empty($fieldXML->html->$htmlOption)) {
5e545f38
CW
404 $field['html'][$htmlOption] = $this->value($htmlOption, $fieldXML->html);
405 }
406 }
407 }
313df5ee
SV
408
409 // in multilingual context popup, we need extra information to create appropriate widget
410 if ($fieldXML->localizable) {
411 if (isset($fieldXML->html)) {
412 $field['widget'] = (array) $fieldXML->html;
413 }
414 else {
415 // default
be2fb01f 416 $field['widget'] = ['type' => 'Text'];
313df5ee
SV
417 }
418 if (isset($fieldXML->required)) {
419 $field['widget']['required'] = $this->value('required', $fieldXML);
420 }
421 }
65c86f7d 422 if (isset($fieldXML->localize_context)) {
423 $field['localize_context'] = $fieldXML->localize_context;
424 }
a9d0587b 425 $field['add'] = $this->value('add', $fieldXML);
5e434adf 426 $field['pseudoconstant'] = $this->value('pseudoconstant', $fieldXML);
9b873358 427 if (!empty($field['pseudoconstant'])) {
5e434adf 428 //ok this is a bit long-winded but it gets there & is consistent with above approach
be2fb01f
CW
429 $field['pseudoconstant'] = [];
430 $validOptions = [
5e434adf
ARW
431 // Fields can specify EITHER optionGroupName OR table, not both
432 // (since declaring optionGroupName means we are using the civicrm_option_value table)
433 'optionGroupName',
434 'table',
435 // If table is specified, keyColumn and labelColumn are also required
436 'keyColumn',
437 'labelColumn',
438 // Non-translated machine name for programmatic lookup. Defaults to 'name' if that column exists
439 'nameColumn',
a8fdb24e
CW
440 // Column to fetch in "abbreviate" context
441 'abbrColumn',
76c1631a 442 // Where clause snippet (will be joined to the rest of the query with AND operator)
5e434adf 443 'condition',
b44e3f84 444 // callback function incase of static arrays
cc6443c4 445 'callback',
14f42e31
CW
446 // Path to options edit form
447 'optionEditPath',
be2fb01f 448 ];
5e434adf 449 foreach ($validOptions as $pseudoOption) {
9b873358 450 if (!empty($fieldXML->pseudoconstant->$pseudoOption)) {
5e434adf
ARW
451 $field['pseudoconstant'][$pseudoOption] = $this->value($pseudoOption, $fieldXML->pseudoconstant);
452 }
453 }
14f42e31
CW
454 if (!isset($field['pseudoconstant']['optionEditPath']) && !empty($field['pseudoconstant']['optionGroupName'])) {
455 $field['pseudoconstant']['optionEditPath'] = 'civicrm/admin/options/' . $field['pseudoconstant']['optionGroupName'];
456 }
5e434adf
ARW
457 // For now, fields that have option lists that are not in the db can simply
458 // declare an empty pseudoconstant tag and we'll add this placeholder.
459 // That field's BAO::buildOptions fn will need to be responsible for generating the option list
460 if (empty($field['pseudoconstant'])) {
461 $field['pseudoconstant'] = 'not in database';
462 }
463 }
464 $fields[$name] = &$field;
465 }
466
2558c2b0 467 /**
100fef9d 468 * @param string $name
2558c2b0
EM
469 *
470 * @return string
471 */
00be9182 472 public function composeTitle($name) {
5e434adf
ARW
473 $names = explode('_', strtolower($name));
474 $title = '';
475 for ($i = 0; $i < count($names); $i++) {
476 if ($names[$i] === 'id' || $names[$i] === 'is') {
477 // id's do not get titles
478 return NULL;
479 }
480
481 if ($names[$i] === 'im') {
482 $names[$i] = 'IM';
483 }
484 else {
485 $names[$i] = ucfirst(trim($names[$i]));
486 }
487
488 $title = $title . ' ' . $names[$i];
489 }
490 return trim($title);
491 }
492
2558c2b0 493 /**
21ca2cb6 494 * @param object $primaryXML
495 * @param array $fields
496 * @param array $table
2558c2b0 497 */
00be9182 498 public function getPrimaryKey(&$primaryXML, &$fields, &$table) {
5e434adf
ARW
499 $name = trim((string ) $primaryXML->name);
500
5e434adf
ARW
501 // set the autoincrement property of the field
502 $auto = $this->value('autoincrement', $primaryXML);
022785d8
JJ
503 if (isset($fields[$name])) {
504 $fields[$name]['autoincrement'] = $auto;
505 }
5e434adf 506 $fields[$name]['autoincrement'] = $auto;
be2fb01f 507 $primaryKey = [
5e434adf
ARW
508 'name' => $name,
509 'autoincrement' => $auto,
be2fb01f 510 ];
022785d8
JJ
511
512 // populate fields
513 foreach ($primaryXML->fieldName as $v) {
514 $fieldName = (string) ($v);
515 $length = (string) ($v['length']);
516 if (strlen($length) > 0) {
517 $fieldName = "$fieldName($length)";
518 }
519 $primaryKey['field'][] = $fieldName;
520 }
521
522 // when field array is empty set it to the name of the primary key.
523 if (empty($primaryKey['field'])) {
524 $primaryKey['field'][] = $name;
525 }
526
527 // all fieldnames have to be defined and should exist in schema.
528 foreach ($primaryKey['field'] as $fieldName) {
529 if (!$fieldName) {
530 echo "Invalid field defination for index $name\n";
531 return;
532 }
533 $parenOffset = strpos($fieldName, '(');
534 if ($parenOffset > 0) {
535 $fieldName = substr($fieldName, 0, $parenOffset);
536 }
537 if (!array_key_exists($fieldName, $fields)) {
538 echo "Table does not contain $fieldName\n";
539 print_r($fields);
540 exit();
541 }
542 }
543
5e434adf
ARW
544 $table['primaryKey'] = &$primaryKey;
545 }
546
2558c2b0
EM
547 /**
548 * @param $indexXML
549 * @param $fields
550 * @param $indices
551 */
00be9182 552 public function getIndex(&$indexXML, &$fields, &$indices) {
5e434adf
ARW
553 //echo "\n\n*******************************************************\n";
554 //echo "entering getIndex\n";
555
be2fb01f 556 $index = [];
5e434adf 557 // empty index name is fine
353ffa53
TO
558 $indexName = trim((string) $indexXML->name);
559 $index['name'] = $indexName;
be2fb01f 560 $index['field'] = [];
5e434adf
ARW
561
562 // populate fields
563 foreach ($indexXML->fieldName as $v) {
2aa397bc
TO
564 $fieldName = (string) ($v);
565 $length = (string) ($v['length']);
5e434adf
ARW
566 if (strlen($length) > 0) {
567 $fieldName = "$fieldName($length)";
568 }
569 $index['field'][] = $fieldName;
570 }
571
572 $index['localizable'] = FALSE;
573 foreach ($index['field'] as $fieldName) {
574 if (isset($fields[$fieldName]) and $fields[$fieldName]['localizable']) {
575 $index['localizable'] = TRUE;
576 break;
577 }
578 }
579
580 // check for unique index
581 if ($this->value('unique', $indexXML)) {
582 $index['unique'] = TRUE;
583 }
584
5e434adf
ARW
585 // field array cannot be empty
586 if (empty($index['field'])) {
587 echo "No fields defined for index $indexName\n";
588 return;
589 }
590
591 // all fieldnames have to be defined and should exist in schema.
592 foreach ($index['field'] as $fieldName) {
593 if (!$fieldName) {
594 echo "Invalid field defination for index $indexName\n";
595 return;
596 }
597 $parenOffset = strpos($fieldName, '(');
598 if ($parenOffset > 0) {
599 $fieldName = substr($fieldName, 0, $parenOffset);
600 }
601 if (!array_key_exists($fieldName, $fields)) {
602 echo "Table does not contain $fieldName\n";
603 print_r($fields);
604 exit();
605 }
606 }
607 $indices[$indexName] = &$index;
608 }
609
2558c2b0
EM
610 /**
611 * @param $foreignXML
612 * @param $fields
613 * @param $foreignKeys
100fef9d 614 * @param string $currentTableName
2558c2b0 615 */
00be9182 616 public function getForeignKey(&$foreignXML, &$fields, &$foreignKeys, &$currentTableName) {
5e434adf
ARW
617 $name = trim((string ) $foreignXML->name);
618
619 /** need to make sure there is a field of type name */
620 if (!array_key_exists($name, $fields)) {
2aa397bc 621 echo "foreign $name in $currentTableName does not have a field definition, ignoring\n";
5e434adf
ARW
622 return;
623 }
624
625 /** need to check for existence of table and key **/
626 $table = trim($this->value('table', $foreignXML));
be2fb01f 627 $foreignKey = [
5e434adf
ARW
628 'name' => $name,
629 'table' => $table,
630 'uniqName' => "FK_{$currentTableName}_{$name}",
631 'key' => trim($this->value('key', $foreignXML)),
632 'import' => $this->value('import', $foreignXML, FALSE),
633 'export' => $this->value('import', $foreignXML, FALSE),
b44e3f84 634 // we do this matching in a separate phase (resolveForeignKeys)
5e434adf
ARW
635 'className' => NULL,
636 'onDelete' => $this->value('onDelete', $foreignXML, FALSE),
be2fb01f 637 ];
5e434adf
ARW
638 $foreignKeys[$name] = &$foreignKey;
639 }
640
2558c2b0
EM
641 /**
642 * @param $foreignXML
643 * @param $dynamicForeignKeys
644 */
00be9182 645 public function getDynamicForeignKey(&$foreignXML, &$dynamicForeignKeys) {
be2fb01f 646 $foreignKey = [
5e434adf
ARW
647 'idColumn' => trim($foreignXML->idColumn),
648 'typeColumn' => trim($foreignXML->typeColumn),
649 'key' => trim($this->value('key', $foreignXML)),
be2fb01f 650 ];
5e434adf
ARW
651 $dynamicForeignKeys[] = $foreignKey;
652 }
653
2558c2b0
EM
654 /**
655 * @param $key
656 * @param $object
657 * @param null $default
658 *
659 * @return null|string
660 */
5e434adf
ARW
661 protected function value($key, &$object, $default = NULL) {
662 if (isset($object->$key)) {
663 return (string ) $object->$key;
664 }
665 return $default;
666 }
667
2558c2b0
EM
668 /**
669 * @param $attributes
670 * @param $object
100fef9d 671 * @param string $name
2558c2b0
EM
672 * @param null $pre
673 * @param null $post
674 */
5e434adf
ARW
675 protected function checkAndAppend(&$attributes, &$object, $name, $pre = NULL, $post = NULL) {
676 if (!isset($object->$name)) {
677 return;
678 }
679
680 $value = $pre . trim($object->$name) . $post;
681 $this->append($attributes, ' ', trim($value));
682 }
683
2558c2b0
EM
684 /**
685 * @param $str
686 * @param $delim
687 * @param $name
688 */
5e434adf
ARW
689 protected function append(&$str, $delim, $name) {
690 if (empty($name)) {
691 return;
692 }
693
694 if (is_array($name)) {
695 foreach ($name as $n) {
696 if (empty($n)) {
697 continue;
698 }
699 if (empty($str)) {
700 $str = $n;
701 }
702 else {
703 $str .= $delim . $n;
704 }
705 }
706 }
707 else {
708 if (empty($str)) {
709 $str = $name;
710 }
711 else {
712 $str .= $delim . $name;
713 }
714 }
715 }
716
717 /**
fe482240 718 * Sets the size property of a textfield.
ea3ddccf 719 *
720 * @param string $fieldXML
721 *
722 * @return null|string
5e434adf
ARW
723 */
724 protected function getSize($fieldXML) {
725 // Extract from <size> tag if supplied
5e545f38 726 if (!empty($fieldXML->html) && $this->value('size', $fieldXML->html)) {
54f5e87f 727 return $this->value('size', $fieldXML->html);
5e434adf
ARW
728 }
729 // Infer from <length> tag if <size> was not explicitly set or was invalid
f53213b2
TM
730 // This map is slightly different from CRM_Core_Form_Renderer::$_sizeMapper
731 // Because we usually want fields to render as smaller than their maxlength
be2fb01f 732 $sizes = [
f53213b2
TM
733 2 => 'TWO',
734 4 => 'FOUR',
735 6 => 'SIX',
736 8 => 'EIGHT',
737 16 => 'TWELVE',
738 32 => 'MEDIUM',
739 64 => 'BIG',
be2fb01f 740 ];
f53213b2
TM
741 foreach ($sizes as $length => $name) {
742 if ($fieldXML->length <= $length) {
743 return "CRM_Utils_Type::$name";
744 }
745 }
746 return 'CRM_Utils_Type::HUGE';
5e434adf 747 }
96025800 748
449c4e6b
CW
749 /**
750 * Converts an entity name to a user friendly string.
751 *
752 * @param string $name
753 * return string
754 */
755 public static function nameToTitle(string $name) {
756 $name = preg_replace('/([a-z])([A-Z])/', '$1 $2', $name);
757 return CRM_Utils_String::pluralize($name);
758 }
759
5e434adf 760}