Merge pull request #4997 from monishdeb/CRM-15536
[civicrm-core.git] / CRM / Core / Reference / Dynamic.php
CommitLineData
11626cf1
TO
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 */
8class CRM_Core_Reference_Dynamic extends CRM_Core_Reference_Basic {
9
a0ee3941
EM
10 /**
11 * @param string $tableName
12 *
13 * @return bool
14 */
11626cf1
TO
15 public function matchesTargetTable($tableName) {
16 return TRUE;
17 }
18
19 /**
20 * Create a query to find references to a particular record
21 *
6a0b768e
TO
22 * @param CRM_Core_DAO $targetDao
23 * The instance for which we want references.
16b10e64
CW
24 * @return CRM_Core_DAO
25 * a query-handle (like the result of CRM_Core_DAO::executeQuery)
11626cf1
TO
26 */
27 public function findReferences($targetDao) {
28 $refColumn = $this->getReferenceKey();
29 $targetColumn = $this->getTargetKey();
30
31 $params = array(
32 1 => array($targetDao->$targetColumn, 'String'),
11626cf1
TO
33 // If anyone complains about $targetDao::getTableName(), then could use
34 // "{get_class($targetDao)}::getTableName();"
35 2 => array($targetDao::getTableName(), 'String'),
36 );
37
38 $sql = <<<EOS
39SELECT id
40FROM {$this->getReferenceTable()}
41WHERE {$refColumn} = %1
42AND {$this->getTypeColumn()} = %2
43EOS;
44
45 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($this->getReferenceTable());
46 $result = CRM_Core_DAO::executeQuery($sql, $params, TRUE, $daoName);
47 return $result;
48 }
1256c139 49
a0ee3941
EM
50 /**
51 * @param CRM_Core_DAO $targetDao
52 *
53 * @return array
54 */
1256c139
TO
55 public function getReferenceCount($targetDao) {
56 $targetColumn = $this->getTargetKey();
57 $params = array(
58 1 => array($targetDao->$targetColumn, 'String'),
1256c139
TO
59 // If anyone complains about $targetDao::getTableName(), then could use
60 // "{get_class($targetDao)}::getTableName();"
61 2 => array($targetDao::getTableName(), 'String'),
62 );
63
64 $sql = <<<EOS
65SELECT count(id)
66FROM {$this->getReferenceTable()}
67WHERE {$this->getReferenceKey()} = %1
68AND {$this->getTypeColumn()} = %2
69EOS;
70
71 return array(
72 'name' => implode(':', array('sql', $this->getReferenceTable(), $this->getReferenceKey())),
73 'type' => get_class($this),
74 'table' => $this->getReferenceTable(),
75 'key' => $this->getReferenceKey(),
21dfd5f5 76 'count' => CRM_Core_DAO::singleValueQuery($sql, $params),
1256c139
TO
77 );
78 }
79
11626cf1 80}