APIv4 - Add SortableEntity and ManagedEntity traits to Navigation menu entity
[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($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 // Special handing of current_domain
114 foreach ($allFields as $fieldName => $field) {
115 if (($field['fk_entity'] ?? NULL) === 'Domain') {
116 $alias = $fieldName . '.name';
117 if (isset($record[$alias]) && $record[$alias] === \CRM_Core_BAO_Domain::getDomain()->name) {
118 unset($record[$alias]);
119 $record[$fieldName] = 'current_domain';
120 }
121 }
122 }
123 $name = ($parentName ?? '') . $entityType . '_' . ($record['name'] ?? count($this->exportedEntities[$entityType]));
124 $result[] = [
125 'name' => $name,
126 'entity' => $entityType,
127 'cleanup' => $this->cleanup,
128 'update' => $this->update,
129 'params' => [
130 'version' => 4,
131 'values' => $record,
132 ],
133 ];
134 // Export entities that reference this one
135 $daoName = CoreUtil::getInfoItem($entityType, 'dao');
136 /** @var \CRM_Core_DAO $dao */
137 $dao = new $daoName();
138 $dao->id = $entityId;
139 // Collect references into arrays keyed by entity type
140 $references = [];
141 foreach ($dao->findReferences() as $reference) {
142 $refEntity = \CRM_Utils_Array::first($reference::fields())['entity'] ?? '';
143 $references[$refEntity][] = $reference;
144 }
145 foreach ($references as $refEntity => $records) {
146 $refApiType = CoreUtil::getInfoItem($refEntity, 'type') ?? [];
147 // Reference must be a ManagedEntity
148 if (!in_array('ManagedEntity', $refApiType, TRUE)) {
149 continue;
150 }
151 $exclude = [];
152 // For sortable entities, order by weight and exclude weight from the export (it will be auto-managed)
153 if (in_array('SortableEntity', $refApiType, TRUE)) {
154 $exclude[] = $weightCol = CoreUtil::getInfoItem($refEntity, 'order_by');
155 usort($records, function($a, $b) use ($weightCol) {
156 if (!isset($a->$weightCol)) {
157 $a->find(TRUE);
158 }
159 if (!isset($b->$weightCol)) {
160 $b->find(TRUE);
161 }
162 return $a->$weightCol < $b->$weightCol ? -1 : 1;
163 });
164 }
165 foreach ($records as $record) {
166 $this->exportRecord($refEntity, $record->id, $result, $name . '_', $exclude);
167 }
168 }
169 }
170
171 /**
172 * If a field has a pseudoconstant list, determine whether it would be better
173 * to use pseudoconstant (field:name) syntax.
174 *
175 * Generally speaking, options with numeric keys are the ones we need to worry about
176 * because auto-increment keys can vary when migrating an entity to a different database.
177 *
178 * But options with string keys tend to be stable,
179 * and it's better not to use the pseudoconstant syntax with these fields because
180 * the option list may not be populated at the time of managed entity reconciliation.
181 *
182 * @param array $field
183 * @return bool
184 */
185 private function shouldUsePseudoconstant(array $field) {
186 if (empty($field['options'])) {
187 return FALSE;
188 }
189 $numericKeys = array_filter(array_keys($field['options']), 'is_numeric');
190 return count($numericKeys) === count($field['options']);
191 }
192
193 /**
194 * @param $entityType
195 * @param bool $loadOptions
196 * @param array $excludeFields
197 * @return array
198 */
199 private function getFieldsForExport($entityType, $loadOptions = FALSE, $excludeFields = []): array {
200 $conditions = [
201 ['type', 'IN', ['Field', 'Custom']],
202 ['readonly', '!=', TRUE],
203 ];
204 if ($excludeFields) {
205 $conditions[] = ['name', 'NOT IN', $excludeFields];
206 }
207 try {
208 return (array) civicrm_api4($entityType, 'getFields', [
209 'action' => 'create',
210 'where' => $conditions,
211 'loadOptions' => $loadOptions,
212 'checkPermissions' => $this->checkPermissions,
213 ])->indexBy('name');
214 }
215 catch (NotImplementedException $e) {
216 return [];
217 }
218 }
219
220 }