Merge pull request #19166 from eileenmcnaughton/cont_type
[civicrm-core.git] / CRM / Core / Reference / Dynamic.php
1 <?php
2
3 /**
4 * Description of a one-way link between two entities
5 *
6 * This is a generic, soft-foreign key based on a pair of columns (entity_id, entity_table).
7 */
8 class CRM_Core_Reference_Dynamic extends CRM_Core_Reference_Basic {
9
10 /**
11 * @param string $tableName
12 *
13 * @return bool
14 */
15 public function matchesTargetTable($tableName) {
16 // FIXME: Shouldn't this check against keys returned by getTargetEntities?
17 return TRUE;
18 }
19
20 /**
21 * @return array
22 * [table_name => EntityName]
23 */
24 public function getTargetEntities(): array {
25 $targetEntities = [];
26 $bao = CRM_Core_DAO_AllCoreTables::getClassForTable($this->refTable);
27 foreach ($bao::buildOptions($this->refTypeColumn) as $table => $label) {
28 $targetEntities[$table] = CRM_Core_DAO_AllCoreTables::getEntityNameForTable($table);
29 }
30 return $targetEntities;
31 }
32
33 /**
34 * Create a query to find references to a particular record.
35 *
36 * @param CRM_Core_DAO $targetDao
37 * The instance for which we want references.
38 * @return CRM_Core_DAO
39 * a query-handle (like the result of CRM_Core_DAO::executeQuery)
40 */
41 public function findReferences($targetDao) {
42 $refColumn = $this->getReferenceKey();
43 $targetColumn = $this->getTargetKey();
44
45 $params = [
46 1 => [$targetDao->$targetColumn, 'String'],
47 // If anyone complains about $targetDao::getTableName(), then could use
48 // "{get_class($targetDao)}::getTableName();"
49 2 => [$targetDao::getTableName(), 'String'],
50 ];
51
52 $sql = <<<EOS
53 SELECT id
54 FROM {$this->getReferenceTable()}
55 WHERE {$refColumn} = %1
56 AND {$this->getTypeColumn()} = %2
57 EOS;
58
59 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($this->getReferenceTable());
60 $result = CRM_Core_DAO::executeQuery($sql, $params, TRUE, $daoName);
61 return $result;
62 }
63
64 /**
65 * @param CRM_Core_DAO $targetDao
66 *
67 * @return array
68 */
69 public function getReferenceCount($targetDao) {
70 $targetColumn = $this->getTargetKey();
71 $params = [
72 1 => [$targetDao->$targetColumn, 'String'],
73 // If anyone complains about $targetDao::getTableName(), then could use
74 // "{get_class($targetDao)}::getTableName();"
75 2 => [$targetDao::getTableName(), 'String'],
76 ];
77
78 $sql = <<<EOS
79 SELECT count(id)
80 FROM {$this->getReferenceTable()}
81 WHERE {$this->getReferenceKey()} = %1
82 AND {$this->getTypeColumn()} = %2
83 EOS;
84
85 return [
86 'name' => implode(':', ['sql', $this->getReferenceTable(), $this->getReferenceKey()]),
87 'type' => get_class($this),
88 'table' => $this->getReferenceTable(),
89 'key' => $this->getReferenceKey(),
90 'count' => CRM_Core_DAO::singleValueQuery($sql, $params),
91 ];
92 }
93
94 }