Merge pull request #21467 from sunilpawar/dev_2833
[civicrm-core.git] / Civi / Api4 / Generic / ExportAction.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
6 | |
7 | This work is published under the GNU AGPLv3 license with some |
8 | permitted exceptions and without any warranty. For full license |
9 | and copyright information, see https://civicrm.org/licensing |
10 +--------------------------------------------------------------------+
11 */
12
13 namespace Civi\Api4\Generic;
14
15 use Civi\API\Exception\NotImplementedException;
16 use Civi\Api4\Utils\CoreUtil;
17
18 /**
19 * Export $ENTITY to civicrm_managed format.
20 *
21 * This action generates an exportable array suitable for use in a .mgd.php file.
22 * The array will include any other entities that reference the $ENTITY.
23 *
24 * @method $this setId(int $id)
25 * @method int getId()
26 * @method $this setCleanup(string $cleanup)
27 * @method string getCleanup()
28 * @method $this setUpdate(string $update)
29 * @method string getUpdate()
30 */
31 class ExportAction extends AbstractAction {
32
33 /**
34 * Id of $ENTITY to export
35 * @var int
36 * @required
37 */
38 protected $id;
39
40 /**
41 * Specify rule for auto-updating managed entity
42 * @var string
43 * @options never,always,unmodified
44 */
45 protected $update = 'unmodified';
46
47 /**
48 * Specify rule for auto-deleting managed entity
49 * @var string
50 * @options never,always,unused
51 */
52 protected $cleanup = 'unused';
53
54 /**
55 * Used to prevent circular references
56 * @var array
57 */
58 private $exportedEntities = [];
59
60 /**
61 * @param \Civi\Api4\Generic\Result $result
62 */
63 public function _run(Result $result) {
64 $this->exportRecord($this->getEntityName(), $this->id, $result);
65 }
66
67 /**
68 * @param string $entityType
69 * @param int $entityId
70 * @param \Civi\Api4\Generic\Result $result
71 * @param string $parentName
72 * @param array $excludeFields
73 */
74 private function exportRecord(string $entityType, int $entityId, Result $result, $parentName = NULL, $excludeFields = []) {
75 if (isset($this->exportedEntities[$entityType][$entityId])) {
76 throw new \API_Exception("Circular reference detected: attempted to export $entityType id $entityId multiple times.");
77 }
78 $this->exportedEntities[$entityType][$entityId] = TRUE;
79 $select = $pseudofields = [];
80 $allFields = $this->getFieldsForExport($entityType, TRUE, $excludeFields);
81 foreach ($allFields as $field) {
82 // Use implicit join syntax but only if the fk entity has a `name` field
83 if (!empty($field['fk_entity']) && array_key_exists('name', $this->getFieldsForExport($field['fk_entity']))) {
84 $select[] = $field['name'] . '.name';
85 $pseudofields[$field['name'] . '.name'] = $field['name'];
86 }
87 // Use pseudoconstant syntax if appropriate
88 elseif ($this->shouldUsePseudoconstant($entityType, $field)) {
89 $select[] = $field['name'] . ':name';
90 $pseudofields[$field['name'] . ':name'] = $field['name'];
91 }
92 elseif (empty($field['fk_entity'])) {
93 $select[] = $field['name'];
94 }
95 }
96 $record = civicrm_api4($entityType, 'get', [
97 'checkPermissions' => $this->checkPermissions,
98 'select' => $select,
99 'where' => [['id', '=', $entityId]],
100 ])->first();
101 if (!$record) {
102 return;
103 }
104 // The get api always returns ID, but it should not be included in an export
105 unset($record['id']);
106 // Null fields should not use joins/pseudoconstants
107 foreach ($pseudofields as $alias => $fieldName) {
108 if (is_null($record[$alias])) {
109 unset($record[$alias]);
110 $record[$fieldName] = NULL;
111 }
112 }
113 // Should references be limited to the current domain?
114 $limitRefsByDomain = $entityType === 'OptionGroup' && \CRM_Core_OptionGroup::isDomainOptionGroup($record['name']) ? \CRM_Core_BAO_Domain::getDomain()->id : FALSE;
115 foreach ($allFields as $fieldName => $field) {
116 if (($field['fk_entity'] ?? NULL) === 'Domain') {
117 $alias = $fieldName . '.name';
118 if (isset($record[$alias])) {
119 // If this entity is for a specific domain, limit references to that same domain
120 if ($fieldName === 'domain_id') {
121 $limitRefsByDomain = \CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Domain', $record[$alias], 'id', 'name');
122 }
123 // Swap current domain for special API keyword
124 if ($record[$alias] === \CRM_Core_BAO_Domain::getDomain()->name) {
125 unset($record[$alias]);
126 $record[$fieldName] = 'current_domain';
127 }
128 }
129 }
130 }
131 $name = ($parentName ?? '') . $entityType . '_' . ($record['name'] ?? count($this->exportedEntities[$entityType]));
132 $result[] = [
133 'name' => $name,
134 'entity' => $entityType,
135 'cleanup' => $this->cleanup,
136 'update' => $this->update,
137 'params' => [
138 'version' => 4,
139 'values' => $record,
140 ],
141 ];
142 // Export entities that reference this one
143 $daoName = CoreUtil::getInfoItem($entityType, 'dao');
144 if ($daoName) {
145 /** @var \CRM_Core_DAO $dao */
146 $dao = new $daoName();
147 $dao->id = $entityId;
148 // Collect references into arrays keyed by entity type
149 $references = [];
150 foreach ($dao->findReferences() as $reference) {
151 $refEntity = \CRM_Utils_Array::first($reference::fields())['entity'] ?? '';
152 // Limit references by domain
153 if (property_exists($reference, 'domain_id')) {
154 if (!isset($reference->domain_id)) {
155 $reference->find(TRUE);
156 }
157 if (isset($reference->domain_id) && $reference->domain_id != $limitRefsByDomain) {
158 continue;
159 }
160 }
161 $references[$refEntity][] = $reference;
162 }
163 foreach ($references as $refEntity => $records) {
164 $refApiType = CoreUtil::getInfoItem($refEntity, 'type') ?? [];
165 // Reference must be a ManagedEntity
166 if (!in_array('ManagedEntity', $refApiType, TRUE)) {
167 continue;
168 }
169 $exclude = [];
170 // For sortable entities, order by weight and exclude weight from the export (it will be auto-managed)
171 if (in_array('SortableEntity', $refApiType, TRUE)) {
172 $exclude[] = $weightCol = CoreUtil::getInfoItem($refEntity, 'order_by');
173 usort($records, function ($a, $b) use ($weightCol) {
174 if (!isset($a->$weightCol)) {
175 $a->find(TRUE);
176 }
177 if (!isset($b->$weightCol)) {
178 $b->find(TRUE);
179 }
180 return $a->$weightCol < $b->$weightCol ? -1 : 1;
181 });
182 }
183 foreach ($records as $record) {
184 $this->exportRecord($refEntity, $record->id, $result, $name . '_', $exclude);
185 }
186 }
187 }
188 }
189
190 /**
191 * If a field has a pseudoconstant list, determine whether it would be better
192 * to use pseudoconstant (field:name) syntax vs plain value.
193 *
194 * @param string $entityType
195 * @param array $field
196 * @return bool
197 */
198 private function shouldUsePseudoconstant(string $entityType, array $field) {
199 if (empty($field['options'])) {
200 return FALSE;
201 }
202 $daoName = CoreUtil::getInfoItem($entityType, 'dao');
203 // Options generated by a callback function tend to be stable,
204 // and the :name property may not be reliable. Use plain value.
205 if ($daoName && !empty($daoName::getSupportedFields()[$field['name']]['pseudoconstant']['callback'])) {
206 return FALSE;
207 }
208 // Options with numeric keys probably refer to auto-increment keys
209 // which vary across different databases. Use :name syntax.
210 $numericKeys = array_filter(array_keys($field['options']), 'is_numeric');
211 return count($numericKeys) === count($field['options']);
212 }
213
214 /**
215 * @param $entityType
216 * @param bool $loadOptions
217 * @param array $excludeFields
218 * @return array
219 */
220 private function getFieldsForExport($entityType, $loadOptions = FALSE, $excludeFields = []): array {
221 $conditions = [
222 ['type', 'IN', ['Field', 'Custom']],
223 ['readonly', '!=', TRUE],
224 ];
225 if ($excludeFields) {
226 $conditions[] = ['name', 'NOT IN', $excludeFields];
227 }
228 try {
229 return (array) civicrm_api4($entityType, 'getFields', [
230 'action' => 'create',
231 'where' => $conditions,
232 'loadOptions' => $loadOptions,
233 'checkPermissions' => $this->checkPermissions,
234 ])->indexBy('name');
235 }
236 catch (NotImplementedException $e) {
237 return [];
238 }
239 }
240
241 }