4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
13 namespace Civi\Api4\Generic
;
15 use Civi\API\Exception\NotImplementedException
;
16 use Civi\Api4\Utils\CoreUtil
;
19 * Export $ENTITY to civicrm_managed format.
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.
24 * @method $this setId(int $id)
26 * @method $this setCleanup(string $cleanup)
27 * @method string getCleanup()
28 * @method $this setUpdate(string $update)
29 * @method string getUpdate()
31 class ExportAction
extends AbstractAction
{
34 * Id of $ENTITY to export
41 * Specify rule for auto-updating managed entity
43 * @options never,always,unmodified
45 protected $update = 'unmodified';
48 * Specify rule for auto-deleting managed entity
50 * @options never,always,unused
52 protected $cleanup = 'unused';
55 * Used to prevent circular references
58 private $exportedEntities = [];
61 * @param \Civi\Api4\Generic\Result $result
63 public function _run(Result
$result) {
64 $this->exportRecord($this->getEntityName(), $this->id
, $result);
68 * @param string $entityType
69 * @param int $entityId
70 * @param \Civi\Api4\Generic\Result $result
71 * @param string $parentName
72 * @param array $excludeFields
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.");
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'];
87 // Use pseudoconstant syntax if appropriate
88 elseif ($this->shouldUsePseudoconstant($field)) {
89 $select[] = $field['name'] . ':name';
90 $pseudofields[$field['name'] . ':name'] = $field['name'];
92 elseif (empty($field['fk_entity'])) {
93 $select[] = $field['name'];
96 $record = civicrm_api4($entityType, 'get', [
97 'checkPermissions' => $this->checkPermissions
,
99 'where' => [['id', '=', $entityId]],
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;
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');
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';
131 $name = ($parentName ??
'') . $entityType . '_' . ($record['name'] ??
count($this->exportedEntities
[$entityType]));
134 'entity' => $entityType,
135 'cleanup' => $this->cleanup
,
136 'update' => $this->update
,
142 // Export entities that reference this one
143 $daoName = CoreUtil
::getInfoItem($entityType, 'dao');
144 /** @var \CRM_Core_DAO $dao */
145 $dao = new $daoName();
146 $dao->id
= $entityId;
147 // Collect references into arrays keyed by entity type
149 foreach ($dao->findReferences() as $reference) {
150 $refEntity = \CRM_Utils_Array
::first($reference::fields())['entity'] ??
'';
151 // Limit references by domain
152 if (property_exists($reference, 'domain_id')) {
153 if (!isset($reference->domain_id
)) {
154 $reference->find(TRUE);
156 if (isset($reference->domain_id
) && $reference->domain_id
!= $limitRefsByDomain) {
160 $references[$refEntity][] = $reference;
162 foreach ($references as $refEntity => $records) {
163 $refApiType = CoreUtil
::getInfoItem($refEntity, 'type') ??
[];
164 // Reference must be a ManagedEntity
165 if (!in_array('ManagedEntity', $refApiType, TRUE)) {
169 // For sortable entities, order by weight and exclude weight from the export (it will be auto-managed)
170 if (in_array('SortableEntity', $refApiType, TRUE)) {
171 $exclude[] = $weightCol = CoreUtil
::getInfoItem($refEntity, 'order_by');
172 usort($records, function($a, $b) use ($weightCol) {
173 if (!isset($a->$weightCol)) {
176 if (!isset($b->$weightCol)) {
179 return $a->$weightCol < $b->$weightCol ?
-1 : 1;
182 foreach ($records as $record) {
183 $this->exportRecord($refEntity, $record->id
, $result, $name . '_', $exclude);
189 * If a field has a pseudoconstant list, determine whether it would be better
190 * to use pseudoconstant (field:name) syntax.
192 * Generally speaking, options with numeric keys are the ones we need to worry about
193 * because auto-increment keys can vary when migrating an entity to a different database.
195 * But options with string keys tend to be stable,
196 * and it's better not to use the pseudoconstant syntax with these fields because
197 * the option list may not be populated at the time of managed entity reconciliation.
199 * @param array $field
202 private function shouldUsePseudoconstant(array $field) {
203 if (empty($field['options'])) {
206 $numericKeys = array_filter(array_keys($field['options']), 'is_numeric');
207 return count($numericKeys) === count($field['options']);
212 * @param bool $loadOptions
213 * @param array $excludeFields
216 private function getFieldsForExport($entityType, $loadOptions = FALSE, $excludeFields = []): array {
218 ['type', 'IN', ['Field', 'Custom']],
219 ['readonly', '!=', TRUE],
221 if ($excludeFields) {
222 $conditions[] = ['name', 'NOT IN', $excludeFields];
225 return (array) civicrm_api4($entityType, 'getFields', [
226 'action' => 'create',
227 'where' => $conditions,
228 'loadOptions' => $loadOptions,
229 'checkPermissions' => $this->checkPermissions
,
232 catch (NotImplementedException
$e) {