[REF] - Add helper function for the repetitive task of fetching multilingual
[civicrm-core.git] / CRM / Core / DAO / AllCoreTables.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
6 | |
7 | This work is published under the GNU AGPLv3 license with some |
8 | permitted exceptions and without any warranty. For full license |
9 | and copyright information, see https://civicrm.org/licensing |
10 +--------------------------------------------------------------------+
11 */
12
13 /**
14 *
15 * @package CRM
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 */
18 class CRM_Core_DAO_AllCoreTables {
19
20 private static $tables = NULL;
21 private static $daoToClass = NULL;
22 private static $entityTypes = NULL;
23
24 /**
25 * Initialise.
26 *
27 * @param bool $fresh
28 */
29 public static function init($fresh = FALSE) {
30 static $init = FALSE;
31 if ($init && !$fresh) {
32 return;
33 }
34 Civi::$statics[__CLASS__] = [];
35
36 $file = preg_replace('/\.php$/', '.data.php', __FILE__);
37 $entityTypes = require $file;
38 CRM_Utils_Hook::entityTypes($entityTypes);
39
40 self::$entityTypes = [];
41 self::$tables = [];
42 self::$daoToClass = [];
43 foreach ($entityTypes as $entityType) {
44 self::registerEntityType(
45 $entityType['name'],
46 $entityType['class'],
47 $entityType['table'],
48 $entityType['fields_callback'] ?? NULL,
49 $entityType['links_callback'] ?? NULL
50 );
51 }
52
53 $init = TRUE;
54 }
55
56 /**
57 * (Quasi-Private) Do not call externally (except for unit-testing)
58 *
59 * @param string $daoName
60 * @param string $className
61 * @param string $tableName
62 * @param string $fields_callback
63 * @param string $links_callback
64 */
65 public static function registerEntityType($daoName, $className, $tableName, $fields_callback = NULL, $links_callback = NULL) {
66 self::$daoToClass[$daoName] = $className;
67 self::$tables[$tableName] = $className;
68 self::$entityTypes[$className] = [
69 'name' => $daoName,
70 'class' => $className,
71 'table' => $tableName,
72 'fields_callback' => $fields_callback,
73 'links_callback' => $links_callback,
74 ];
75 }
76
77 /**
78 * @return array
79 * Ex: $result['CRM_Contact_DAO_Contact']['table'] == 'civicrm_contact';
80 */
81 public static function get() {
82 self::init();
83 return self::$entityTypes;
84 }
85
86 /**
87 * @return array
88 * List of SQL table names.
89 */
90 public static function tables() {
91 self::init();
92 return self::$tables;
93 }
94
95 /**
96 * @return array
97 * List of indices.
98 */
99 public static function indices($localize = TRUE) {
100 $indices = [];
101 self::init();
102 foreach (self::$daoToClass as $class) {
103 if (is_callable([$class, 'indices'])) {
104 $indices[$class::getTableName()] = $class::indices($localize);
105 }
106 }
107 return $indices;
108 }
109
110 /**
111 * Modify indices to account for localization options.
112 *
113 * @param string $class DAO class
114 * @param array $originalIndices index definitions before localization
115 *
116 * @return array
117 * index definitions after localization
118 */
119 public static function multilingualize($class, $originalIndices) {
120 $locales = CRM_Core_I18n::getMultilingual();
121 if (!$locales) {
122 return $originalIndices;
123 }
124 $classFields = $class::fields();
125
126 $finalIndices = [];
127 foreach ($originalIndices as $index) {
128 if ($index['localizable']) {
129 foreach ($locales as $locale) {
130 $localIndex = $index;
131 $localIndex['name'] .= "_" . $locale;
132 $fields = [];
133 foreach ($localIndex['field'] as $field) {
134 $baseField = explode('(', $field);
135 if ($classFields[$baseField[0]]['localizable']) {
136 // field name may have eg (3) at end for prefix length
137 // last_name => last_name_fr_FR
138 // last_name(3) => last_name_fr_FR(3)
139 $fields[] = preg_replace('/^([^(]+)(\(\d+\)|)$/', '${1}_' . $locale . '${2}', $field);
140 }
141 else {
142 $fields[] = $field;
143 }
144 }
145 $localIndex['field'] = $fields;
146 $finalIndices[$localIndex['name']] = $localIndex;
147 }
148 }
149 else {
150 $finalIndices[$index['name']] = $index;
151 }
152 }
153 CRM_Core_BAO_SchemaHandler::addIndexSignature(self::getTableForClass($class), $finalIndices);
154 return $finalIndices;
155 }
156
157 /**
158 * @return array
159 * Mapping from brief-names to class-names.
160 * Ex: $result['Contact'] == 'CRM_Contact_DAO_Contact'.
161 */
162 public static function daoToClass() {
163 self::init();
164 return self::$daoToClass;
165 }
166
167 /**
168 * @return array
169 * Mapping from table-names to class-names.
170 * Ex: $result['civicrm_contact'] == 'CRM_Contact_DAO_Contact'.
171 */
172 public static function getCoreTables() {
173 return self::tables();
174 }
175
176 /**
177 * Determine whether $tableName is a core table.
178 *
179 * @param string $tableName
180 * @return bool
181 */
182 public static function isCoreTable($tableName) {
183 return array_key_exists($tableName, self::tables());
184 }
185
186 /**
187 * Get the DAO for a BAO class.
188 *
189 * @param string $baoName
190 *
191 * @return string|CRM_Core_DAO
192 */
193 public static function getCanonicalClassName($baoName) {
194 return str_replace('_BAO_', '_DAO_', $baoName);
195 }
196
197 /**
198 * Get the BAO for a DAO class.
199 *
200 * @param string $daoName
201 *
202 * @return string|CRM_Core_DAO
203 */
204 public static function getBAOClassName($daoName) {
205 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
206 return class_exists($baoName) ? $baoName : $daoName;
207 }
208
209 /**
210 * Convert possibly underscore separated words to camel case with special handling for 'UF'
211 * e.g membership_payment returns MembershipPayment
212 *
213 * @param string $name
214 * @param bool $legacyV3
215 * @return string
216 */
217 public static function convertEntityNameToCamel(string $name, $legacyV3 = FALSE): string {
218 // This map only applies to APIv3
219 $map = [
220 'acl' => 'Acl',
221 'ACL' => 'Acl',
222 'im' => 'Im',
223 'IM' => 'Im',
224 ];
225 if ($legacyV3 && isset($map[$name])) {
226 return $map[$name];
227 }
228
229 $fragments = explode('_', $name);
230 foreach ($fragments as & $fragment) {
231 $fragment = ucfirst($fragment);
232 // Special case: UFGroup, UFJoin, UFMatch, UFField (if passed in without underscores)
233 if (strpos($fragment, 'Uf') === 0 && strlen($name) > 2) {
234 $fragment = 'UF' . ucfirst(substr($fragment, 2));
235 }
236 }
237 // Special case: UFGroup, UFJoin, UFMatch, UFField (if passed in underscore-separated)
238 if ($fragments[0] === 'Uf') {
239 $fragments[0] = 'UF';
240 }
241 return implode('', $fragments);
242 }
243
244 /**
245 * Convert CamelCase to snake_case, with special handling for some entity names.
246 *
247 * Eg. Activity returns activity
248 * UFGroup returns uf_group
249 * OptionValue returns option_value
250 *
251 * @param string $name
252 *
253 * @return string
254 */
255 public static function convertEntityNameToLower(string $name): string {
256 if ($name === strtolower($name)) {
257 return $name;
258 }
259 if ($name === 'PCP' || $name === 'IM' || $name === 'ACL') {
260 return strtolower($name);
261 }
262 return strtolower(ltrim(str_replace('U_F',
263 'uf',
264 // That's CamelCase, beside an odd UFCamel that is expected as uf_camel
265 preg_replace('/(?=[A-Z])/', '_$0', $name)
266 ), '_'));
267 }
268
269 /**
270 * Get a list of all DAO classes.
271 *
272 * @return array
273 * List of class names.
274 */
275 public static function getClasses() {
276 return array_values(self::daoToClass());
277 }
278
279 /**
280 * Get the classname for the table.
281 *
282 * @param string $tableName
283 * @return string
284 */
285 public static function getClassForTable($tableName) {
286 //CRM-19677: on multilingual setup, trim locale from $tableName to fetch class name
287 if (CRM_Core_I18n::isMultilingual()) {
288 global $dbLocale;
289 $tableName = str_replace($dbLocale, '', $tableName);
290 }
291 return CRM_Utils_Array::value($tableName, self::tables());
292 }
293
294 /**
295 * Given a brief-name, determine the full class-name.
296 *
297 * @param string $daoName
298 * Ex: 'Contact'.
299 * @return CRM_Core_DAO|NULL
300 * Ex: 'CRM_Contact_DAO_Contact'.
301 */
302 public static function getFullName($daoName) {
303 return CRM_Utils_Array::value($daoName, self::daoToClass());
304 }
305
306 /**
307 * Given a full class-name, determine the brief-name.
308 *
309 * @param string $className
310 * Ex: 'CRM_Contact_DAO_Contact'.
311 * @return string|NULL
312 * Ex: 'Contact'.
313 */
314 public static function getBriefName($className) {
315 $className = self::getCanonicalClassName($className);
316 return array_search($className, self::daoToClass(), TRUE) ?: NULL;
317 }
318
319 /**
320 * @param string $className DAO or BAO name
321 * @return string|FALSE SQL table name
322 */
323 public static function getTableForClass($className) {
324 return array_search(self::getCanonicalClassName($className),
325 self::tables());
326 }
327
328 /**
329 * Convert the entity name into a table name.
330 *
331 * @param string $entityBriefName
332 *
333 * @return FALSE|string
334 */
335 public static function getTableForEntityName($entityBriefName) {
336 return self::getTableForClass(self::getFullName($entityBriefName));
337 }
338
339 /**
340 * Reinitialise cache.
341 *
342 * @param bool $fresh
343 */
344 public static function reinitializeCache($fresh = FALSE) {
345 self::init($fresh);
346 }
347
348 /**
349 * (Quasi-Private) Do not call externally. For use by DAOs.
350 *
351 * @param string $dao
352 * Ex: 'CRM_Core_DAO_Address'.
353 * @param string $labelName
354 * Ex: 'address'.
355 * @param bool $prefix
356 * @param array $foreignDAOs
357 * @return array
358 */
359 public static function getExports($dao, $labelName, $prefix, $foreignDAOs) {
360 // Bug-level compatibility -- or sane behavior?
361 $cacheKey = $dao . ':export';
362 // $cacheKey = $dao . ':' . ($prefix ? 'export-prefix' : 'export');
363
364 if (!isset(Civi::$statics[__CLASS__][$cacheKey])) {
365 $exports = [];
366 $fields = $dao::fields();
367
368 foreach ($fields as $name => $field) {
369 if (!empty($field['export'])) {
370 if ($prefix) {
371 $exports[$labelName] = & $fields[$name];
372 }
373 else {
374 $exports[$name] = & $fields[$name];
375 }
376 }
377 }
378
379 foreach ($foreignDAOs as $foreignDAO) {
380 $exports = array_merge($exports, $foreignDAO::export(TRUE));
381 }
382
383 Civi::$statics[__CLASS__][$cacheKey] = $exports;
384 }
385 return Civi::$statics[__CLASS__][$cacheKey];
386 }
387
388 /**
389 * (Quasi-Private) Do not call externally. For use by DAOs.
390 *
391 * @param string $dao
392 * Ex: 'CRM_Core_DAO_Address'.
393 * @param string $labelName
394 * Ex: 'address'.
395 * @param bool $prefix
396 * @param array $foreignDAOs
397 * @return array
398 */
399 public static function getImports($dao, $labelName, $prefix, $foreignDAOs) {
400 // Bug-level compatibility -- or sane behavior?
401 $cacheKey = $dao . ':import';
402 // $cacheKey = $dao . ':' . ($prefix ? 'import-prefix' : 'import');
403
404 if (!isset(Civi::$statics[__CLASS__][$cacheKey])) {
405 $imports = [];
406 $fields = $dao::fields();
407
408 foreach ($fields as $name => $field) {
409 if (!empty($field['import'])) {
410 if ($prefix) {
411 $imports[$labelName] = & $fields[$name];
412 }
413 else {
414 $imports[$name] = & $fields[$name];
415 }
416 }
417 }
418
419 foreach ($foreignDAOs as $foreignDAO) {
420 $imports = array_merge($imports, $foreignDAO::import(TRUE));
421 }
422
423 Civi::$statics[__CLASS__][$cacheKey] = $imports;
424 }
425 return Civi::$statics[__CLASS__][$cacheKey];
426 }
427
428 /**
429 * (Quasi-Private) Do not call externally. For use by DAOs.
430 *
431 * Apply any third-party alterations to the `fields()`.
432 *
433 * @param string $className
434 * @param string $event
435 * @param mixed $values
436 */
437 public static function invoke($className, $event, &$values) {
438 self::init();
439 if (isset(self::$entityTypes[$className][$event])) {
440 foreach (self::$entityTypes[$className][$event] as $filter) {
441 $args = [$className, &$values];
442 \Civi\Core\Resolver::singleton()->call($filter, $args);
443 }
444 }
445 }
446
447 }