CRM-14478 - Add CRM_Core_DAO::getReferenceCounts()
[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 public function matchesTargetTable($tableName) {
11 return TRUE;
12 }
13
14 /**
15 * Create a query to find references to a particular record
16 *
17 * @param CRM_Core_DAO $targetDao the instance for which we want references
18 * @return CRM_Core_DAO a query-handle (like the result of CRM_Core_DAO::executeQuery)
19 */
20 public function findReferences($targetDao) {
21 $refColumn = $this->getReferenceKey();
22 $targetColumn = $this->getTargetKey();
23
24 $params = array(
25 1 => array($targetDao->$targetColumn, 'String'),
26
27 // If anyone complains about $targetDao::getTableName(), then could use
28 // "{get_class($targetDao)}::getTableName();"
29 2 => array($targetDao::getTableName(), 'String'),
30 );
31
32 $sql = <<<EOS
33 SELECT id
34 FROM {$this->getReferenceTable()}
35 WHERE {$refColumn} = %1
36 AND {$this->getTypeColumn()} = %2
37 EOS;
38
39 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($this->getReferenceTable());
40 $result = CRM_Core_DAO::executeQuery($sql, $params, TRUE, $daoName);
41 return $result;
42 }
43
44 public function getReferenceCount($targetDao) {
45 $targetColumn = $this->getTargetKey();
46 $params = array(
47 1 => array($targetDao->$targetColumn, 'String'),
48
49 // If anyone complains about $targetDao::getTableName(), then could use
50 // "{get_class($targetDao)}::getTableName();"
51 2 => array($targetDao::getTableName(), 'String'),
52 );
53
54 $sql = <<<EOS
55 SELECT count(id)
56 FROM {$this->getReferenceTable()}
57 WHERE {$this->getReferenceKey()} = %1
58 AND {$this->getTypeColumn()} = %2
59 EOS;
60
61 return array(
62 'name' => implode(':', array('sql', $this->getReferenceTable(), $this->getReferenceKey())),
63 'type' => get_class($this),
64 'table' => $this->getReferenceTable(),
65 'key' => $this->getReferenceKey(),
66 'count' => CRM_Core_DAO::singleValueQuery($sql, $params)
67 );
68 }
69
70 }