Merge pull request #19219 from colemanw/targetTableFix
[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 $targetTables = (array) $bao::buildOptions($this->refTypeColumn);
28 foreach ($targetTables as $table => $label) {
29 $targetEntities[$table] = CRM_Core_DAO_AllCoreTables::getEntityNameForTable($table);
30 }
31 return $targetEntities;
32 }
33
34 /**
35 * Create a query to find references to a particular record.
36 *
37 * @param CRM_Core_DAO $targetDao
38 * The instance for which we want references.
39 * @return CRM_Core_DAO
40 * a query-handle (like the result of CRM_Core_DAO::executeQuery)
41 */
42 public function findReferences($targetDao) {
43 $refColumn = $this->getReferenceKey();
44 $targetColumn = $this->getTargetKey();
45
46 $params = [
47 1 => [$targetDao->$targetColumn, 'String'],
48 // If anyone complains about $targetDao::getTableName(), then could use
49 // "{get_class($targetDao)}::getTableName();"
50 2 => [$targetDao::getTableName(), 'String'],
51 ];
52
53 $sql = <<<EOS
54 SELECT id
55 FROM {$this->getReferenceTable()}
56 WHERE {$refColumn} = %1
57 AND {$this->getTypeColumn()} = %2
58 EOS;
59
60 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($this->getReferenceTable());
61 $result = CRM_Core_DAO::executeQuery($sql, $params, TRUE, $daoName);
62 return $result;
63 }
64
65 /**
66 * @param CRM_Core_DAO $targetDao
67 *
68 * @return array
69 */
70 public function getReferenceCount($targetDao) {
71 $targetColumn = $this->getTargetKey();
72 $params = [
73 1 => [$targetDao->$targetColumn, 'String'],
74 // If anyone complains about $targetDao::getTableName(), then could use
75 // "{get_class($targetDao)}::getTableName();"
76 2 => [$targetDao::getTableName(), 'String'],
77 ];
78
79 $sql = <<<EOS
80 SELECT count(id)
81 FROM {$this->getReferenceTable()}
82 WHERE {$this->getReferenceKey()} = %1
83 AND {$this->getTypeColumn()} = %2
84 EOS;
85
86 return [
87 'name' => implode(':', ['sql', $this->getReferenceTable(), $this->getReferenceKey()]),
88 'type' => get_class($this),
89 'table' => $this->getReferenceTable(),
90 'key' => $this->getReferenceKey(),
91 'count' => CRM_Core_DAO::singleValueQuery($sql, $params),
92 ];
93 }
94
95 }