summaryrefslogtreecommitdiff
path: root/www/crm/wp-content/plugins/civicrm/civicrm/ext/api4/Civi/Api4/Service/Schema/SchemaMapBuilder.php
blob: b578b73a449c06498674c67dc0d2ef5fe91231c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
<?php

namespace Civi\Api4\Service\Schema;

use Civi\Api4\Entity;
use Civi\Api4\Event\Events;
use Civi\Api4\Event\SchemaMapBuildEvent;
use Civi\Api4\Service\Schema\Joinable\CustomGroupJoinable;
use Civi\Api4\Service\Schema\Joinable\Joinable;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Civi\Api4\Service\Schema\Joinable\OptionValueJoinable;
use CRM_Core_DAO_AllCoreTables as TableHelper;
use CRM_Utils_Array as UtilsArray;

class SchemaMapBuilder {
  /**
   * @var EventDispatcherInterface
   */
  protected $dispatcher;
  /**
   * @var array
   */
  protected $apiEntities;

  /**
   * @param EventDispatcherInterface $dispatcher
   */
  public function __construct(EventDispatcherInterface $dispatcher) {
    $this->dispatcher = $dispatcher;
    $this->apiEntities = array_keys((array) Entity::get()->setCheckPermissions(FALSE)->addSelect('name')->execute()->indexBy('name'));
  }

  /**
   * @return SchemaMap
   */
  public function build() {
    $map = new SchemaMap();
    $this->loadTables($map);

    $event = new SchemaMapBuildEvent($map);
    $this->dispatcher->dispatch(Events::SCHEMA_MAP_BUILD, $event);

    return $map;
  }

  /**
   * Add all tables and joins
   *
   * @param SchemaMap $map
   */
  private function loadTables(SchemaMap $map) {
    /** @var \CRM_Core_DAO $daoName */
    foreach (TableHelper::get() as $daoName => $data) {
      $table = new Table($data['table']);
      foreach ($daoName::fields() as $field => $fieldData) {
        $this->addJoins($table, $field, $fieldData);
      }
      $map->addTable($table);
      if (in_array($data['name'], $this->apiEntities)) {
        $this->addCustomFields($map, $table, $data['name']);
      }
    }

    $this->addBackReferences($map);
  }

  /**
   * @param Table $table
   * @param string $field
   * @param array $data
   */
  private function addJoins(Table $table, $field, array $data) {
    $fkClass = UtilsArray::value('FKClassName', $data);

    // can there be multiple methods e.g. pseudoconstant and fkclass
    if ($fkClass) {
      $tableName = TableHelper::getTableForClass($fkClass);
      $fkKey = UtilsArray::value('FKKeyColumn', $data, 'id');
      $alias = str_replace('_id', '', $field);
      $joinable = new Joinable($tableName, $fkKey, $alias);
      $joinable->setJoinType($joinable::JOIN_TYPE_MANY_TO_ONE);
      $table->addTableLink($field, $joinable);
    }
    elseif (UtilsArray::value('pseudoconstant', $data)) {
      $this->addPseudoConstantJoin($table, $field, $data);
    }
  }

  /**
   * @param Table $table
   * @param string $field
   * @param array $data
   */
  private function addPseudoConstantJoin(Table $table, $field, array $data) {
    $pseudoConstant = UtilsArray::value('pseudoconstant', $data);
    $tableName = UtilsArray::value('table', $pseudoConstant);
    $optionGroupName = UtilsArray::value('optionGroupName', $pseudoConstant);
    $keyColumn = UtilsArray::value('keyColumn', $pseudoConstant, 'id');

    if ($tableName) {
      $alias = str_replace('civicrm_', '', $tableName);
      $joinable = new Joinable($tableName, $keyColumn, $alias);
      $condition = UtilsArray::value('condition', $pseudoConstant);
      if ($condition) {
        $joinable->addCondition($condition);
      }
      $table->addTableLink($field, $joinable);
    }
    elseif ($optionGroupName) {
      $keyColumn = UtilsArray::value('keyColumn', $pseudoConstant, 'value');
      $joinable = new OptionValueJoinable($optionGroupName, NULL, $keyColumn);

      if (!empty($data['serialize'])) {
        $joinable->setJoinType($joinable::JOIN_TYPE_ONE_TO_MANY);
      }

      $table->addTableLink($field, $joinable);
    }
  }

  /**
   * Loop through existing links and provide link from the other side
   *
   * @param SchemaMap $map
   */
  private function addBackReferences(SchemaMap $map) {
    foreach ($map->getTables() as $table) {
      foreach ($table->getTableLinks() as $link) {
        // there are too many possible joins from option value so skip
        if ($link instanceof OptionValueJoinable) {
          continue;
        }

        $target = $map->getTableByName($link->getTargetTable());
        $tableName = $link->getBaseTable();
        $plural = str_replace('civicrm_', '', $this->getPlural($tableName));
        $joinable = new Joinable($tableName, $link->getBaseColumn(), $plural);
        $joinable->setJoinType($joinable::JOIN_TYPE_ONE_TO_MANY);
        $target->addTableLink($link->getTargetColumn(), $joinable);
      }
    }
  }

  /**
   * Simple implementation of pluralization.
   * Could be replaced with symfony/inflector
   *
   * @param string $singular
   *
   * @return string
   */
  private function getPlural($singular) {
    $last_letter = substr($singular, -1);
    switch ($last_letter) {
      case 'y':
        return substr($singular, 0, -1) . 'ies';

      case 's':
        return $singular . 'es';

      default:
        return $singular . 's';
    }
  }

  /**
   * @param \Civi\Api4\Service\Schema\SchemaMap $map
   * @param \Civi\Api4\Service\Schema\Table $baseTable
   * @param string $entity
   */
  private function addCustomFields(SchemaMap $map, Table $baseTable, $entity) {
    // Don't be silly
    if (!array_key_exists($entity, \CRM_Core_SelectValues::customGroupExtends())) {
      return;
    }
    $queryEntity = (array) $entity;
    if ($entity == 'Contact') {
      $queryEntity = ['Contact', 'Individual', 'Organization', 'Household'];
    }
    $fieldData = \CRM_Utils_SQL_Select::from('civicrm_custom_field f')
      ->join('custom_group', 'INNER JOIN civicrm_custom_group g ON g.id = f.custom_group_id')
      ->select(['g.name as custom_group_name', 'g.table_name', 'g.is_multiple', 'f.name', 'label', 'column_name', 'option_group_id'])
      ->where('g.extends IN (@entity)', ['@entity' => $queryEntity])
      ->where('g.is_active')
      ->where('f.is_active')
      ->execute();

    $links = [];

    while ($fieldData->fetch()) {
      $tableName = $fieldData->table_name;

      $customTable = $map->getTableByName($tableName);
      if (!$customTable) {
        $customTable = new Table($tableName);
      }

      if (!empty($fieldData->option_group_id)) {
        $optionValueJoinable = new OptionValueJoinable($fieldData->option_group_id, $fieldData->label);
        $customTable->addTableLink($fieldData->column_name, $optionValueJoinable);
      }

      $map->addTable($customTable);

      $alias = $fieldData->custom_group_name;
      $links[$alias]['tableName'] = $tableName;
      $links[$alias]['isMultiple'] = !empty($fieldData->is_multiple);
      $links[$alias]['columns'][$fieldData->name] = $fieldData->column_name;
    }

    foreach ($links as $alias => $link) {
      $joinable = new CustomGroupJoinable($link['tableName'], $alias, $link['isMultiple'], $entity, $link['columns']);
      $baseTable->addTableLink('id', $joinable);
    }
  }

}