CRM-14478 - Add CRM_Core_DAO::getReferenceCounts()
[civicrm-core.git] / CRM / Core / Reference / Basic.php
1 <?php
2
3 /**
4 * Description of a one-way link between two entities
5 *
6 * This is a basic SQL foreign key.
7 */
8 class CRM_Core_Reference_Basic implements CRM_Core_Reference_Interface {
9 protected $refTable;
10 protected $refKey;
11 protected $refTypeColumn;
12 protected $targetTable;
13 protected $targetKey;
14
15 function __construct($refTable, $refKey, $targetTable = NULL, $targetKey = 'id', $refTypeColumn = NULL) {
16 $this->refTable = $refTable;
17 $this->refKey = $refKey;
18 $this->targetTable = $targetTable;
19 $this->targetKey = $targetKey;
20 $this->refTypeColumn = $refTypeColumn;
21 }
22
23 function getReferenceTable() {
24 return $this->refTable;
25 }
26
27 function getReferenceKey() {
28 return $this->refKey;
29 }
30
31 function getTypeColumn() {
32 return $this->refTypeColumn;
33 }
34
35 function getTargetTable() {
36 return $this->targetTable;
37 }
38
39 function getTargetKey() {
40 return $this->targetKey;
41 }
42
43 public function matchesTargetTable($tableName) {
44 return ($this->getTargetTable() === $tableName);
45 }
46
47 public function findReferences($targetDao) {
48 $targetColumn = $this->getTargetKey();
49 $params = array(
50 1 => array($targetDao->$targetColumn, 'String')
51 );
52 $sql = <<<EOS
53 SELECT id
54 FROM {$this->getReferenceTable()}
55 WHERE {$this->getReferenceKey()} = %1
56 EOS;
57
58 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($this->getReferenceTable());
59 $result = CRM_Core_DAO::executeQuery($sql, $params, TRUE, $daoName);
60 return $result;
61 }
62
63 public function getReferenceCount($targetDao) {
64 $targetColumn = $this->getTargetKey();
65 $params = array(
66 1 => array($targetDao->$targetColumn, 'String')
67 );
68 $sql = <<<EOS
69 SELECT count(id)
70 FROM {$this->getReferenceTable()}
71 WHERE {$this->getReferenceKey()} = %1
72 EOS;
73
74 return array(
75 'name' => implode(':', array('sql', $this->getReferenceTable(), $this->getReferenceKey())),
76 'type' => get_class($this),
77 'table' => $this->getReferenceTable(),
78 'key' => $this->getReferenceKey(),
79 'count' => CRM_Core_DAO::singleValueQuery($sql, $params)
80 );
81 }
82 }