APIv4 - Add explicit joins
[civicrm-core.git] / Civi / Api4 / Utils / FormattingUtil.php
index 89f4c7c54bd0cd7063e172a17a0a0e75f4f554e2..b3cd5ecd0528b4d203dee505aae2fd2de4a42ab5 100644 (file)
@@ -34,12 +34,11 @@ class FormattingUtil {
   /**
    * Massage values into the format the BAO expects for a write operation
    *
-   * @param $params
-   * @param $entity
-   * @param $fields
+   * @param array $params
+   * @param array $fields
    * @throws \API_Exception
    */
-  public static function formatWriteParams(&$params, $entity, $fields) {
+  public static function formatWriteParams(&$params, $fields) {
     foreach ($fields as $name => $field) {
       if (!empty($params[$name])) {
         $value =& $params[$name];
@@ -47,7 +46,7 @@ class FormattingUtil {
         if ($value === 'null') {
           $value = 'Null';
         }
-        self::formatInputValue($value, $name, $field, $entity);
+        self::formatInputValue($value, $name, $field);
         // Ensure we have an array for serialized fields
         if (!empty($field['serialize'] && !is_array($value))) {
           $value = (array) $value;
@@ -81,24 +80,23 @@ class FormattingUtil {
    * @param $value
    * @param string $fieldName
    * @param array $fieldSpec
-   * @param string $entity
-   *   Ex: 'Contact', 'Domain'
    * @throws \API_Exception
    */
-  public static function formatInputValue(&$value, $fieldName, $fieldSpec, $entity) {
+  public static function formatInputValue(&$value, $fieldName, $fieldSpec) {
     // Evaluate pseudoconstant suffix
     $suffix = strpos($fieldName, ':');
     if ($suffix) {
       $options = self::getPseudoconstantList($fieldSpec['entity'], $fieldSpec['name'], substr($fieldName, $suffix + 1));
       $value = self::replacePseudoconstant($options, $value, TRUE);
+      return;
     }
     elseif (is_array($value)) {
       foreach ($value as &$val) {
-        self::formatInputValue($val, $fieldName, $fieldSpec, $entity);
+        self::formatInputValue($val, $fieldName, $fieldSpec);
       }
       return;
     }
-    $fk = $fieldSpec['name'] == 'id' ? $entity : $fieldSpec['fk_entity'] ?? NULL;
+    $fk = $fieldSpec['name'] == 'id' ? $fieldSpec['entity'] : $fieldSpec['fk_entity'] ?? NULL;
 
     if ($fk === 'Domain' && $value === 'current_domain') {
       $value = \CRM_Core_Config::domainID();
@@ -140,10 +138,7 @@ class FormattingUtil {
   public static function formatOutputValues(&$results, $fields, $entity, $action = 'get') {
     $fieldOptions = [];
     foreach ($results as &$result) {
-      // Remove inapplicable contact fields
-      if ($entity === 'Contact' && !empty($result['contact_type'])) {
-        \CRM_Utils_Array::remove($result, self::contactFieldsToRemove($result['contact_type']));
-      }
+      $contactTypePaths = [];
       foreach ($result as $fieldExpr => $value) {
         $field = $fields[$fieldExpr] ?? NULL;
         $dataType = $field['data_type'] ?? ($fieldExpr == 'id' ? 'Integer' : NULL);
@@ -163,9 +158,18 @@ class FormattingUtil {
           if (isset($fieldOptions[$fieldExpr])) {
             $value = self::replacePseudoconstant($fieldOptions[$fieldExpr], $value);
           }
+          // Keep track of contact types for self::contactFieldsToRemove
+          if ($value && isset($field['entity']) && $field['entity'] === 'Contact' && $field['name'] === 'contact_type') {
+            $prefix = strrpos($fieldExpr, '.');
+            $contactTypePaths[$prefix ? substr($fieldExpr, 0, $prefix + 1) : ''] = $value;
+          }
         }
         $result[$fieldExpr] = self::convertDataType($value, $dataType);
       }
+      // Remove inapplicable contact fields
+      foreach ($contactTypePaths as $prefix => $contactType) {
+        \CRM_Utils_Array::remove($result, self::contactFieldsToRemove($contactType, $prefix));
+      }
     }
   }
 
@@ -175,15 +179,16 @@ class FormattingUtil {
    * @param string $entity
    *   Name of api entity
    * @param string $fieldName
-   * @param string $optionValue
+   * @param string $valueType
+   *   name|label|abbr from self::$pseudoConstantContexts
    * @param array $params
    *   Other values for this object
    * @param string $action
    * @return array
    * @throws \API_Exception
    */
-  public static function getPseudoconstantList($entity, $fieldName, $optionValue, $params = [], $action = 'get') {
-    $context = self::$pseudoConstantContexts[$optionValue] ?? NULL;
+  public static function getPseudoconstantList($entity, $fieldName, $valueType, $params = [], $action = 'get') {
+    $context = self::$pseudoConstantContexts[$valueType] ?? NULL;
     if (!$context) {
       throw new \API_Exception('Illegal expression');
     }
@@ -192,8 +197,8 @@ class FormattingUtil {
     if ($baoName) {
       $options = $baoName::buildOptions($fieldName, $context, $params);
     }
-    // Fallback for non-bao based entities
-    if (!isset($options)) {
+    // Fallback for option lists that exist in the api but not the BAO - note: $valueType gets ignored here
+    if (!isset($options) || $options === FALSE) {
       $options = civicrm_api4($entity, 'getFields', ['action' => $action, 'loadOptions' => TRUE, 'where' => [['name', '=', $fieldName]]])[0]['options'] ?? NULL;
     }
     if (is_array($options)) {
@@ -257,19 +262,33 @@ class FormattingUtil {
   }
 
   /**
+   * Lists all field names (including suffixed variants) that should be removed for a given contact type.
+   *
    * @param string $contactType
+   *   Individual|Organization|Household
+   * @param string $prefix
+   *   Path at which these fields are found, e.g. "address.contact."
    * @return array
    */
-  public static function contactFieldsToRemove($contactType) {
+  public static function contactFieldsToRemove($contactType, $prefix) {
     if (!isset(\Civi::$statics[__CLASS__][__FUNCTION__][$contactType])) {
       \Civi::$statics[__CLASS__][__FUNCTION__][$contactType] = [];
       foreach (\CRM_Contact_DAO_Contact::fields() as $field) {
         if (!empty($field['contactType']) && $field['contactType'] != $contactType) {
           \Civi::$statics[__CLASS__][__FUNCTION__][$contactType][] = $field['name'];
+          // Include suffixed variants like prefix_id:label
+          if (!empty($field['pseudoconstant'])) {
+            foreach (array_keys(self::$pseudoConstantContexts) as $suffix) {
+              \Civi::$statics[__CLASS__][__FUNCTION__][$contactType][] = $field['name'] . ':' . $suffix;
+            }
+          }
         }
       }
     }
-    return \Civi::$statics[__CLASS__][__FUNCTION__][$contactType];
+    // Add prefix paths
+    return array_map(function($name) use ($prefix) {
+      return $prefix . $name;
+    }, \Civi::$statics[__CLASS__][__FUNCTION__][$contactType]);
   }
 
 }