Merge pull request #18147 from eileenmcnaughton/ex_type
[civicrm-core.git] / CRM / Export / BAO / ExportProcessor.php
index 58aa78ba168a6bfe98bb09182a356613ee2a37a2..7c2fbb8592179cae4083eb9db6c9078499d843b8 100644 (file)
@@ -639,6 +639,12 @@ class CRM_Export_BAO_ExportProcessor {
     $queryFields['world_region']['context'] = 'country';
     $queryFields['state_province']['context'] = 'province';
     $queryFields['contact_id'] = ['title' => ts('Contact ID'), 'type' => CRM_Utils_Type::T_INT];
+    $queryFields['tags']['type'] = CRM_Utils_Type::T_LONGTEXT;
+    $queryFields['groups']['type'] = CRM_Utils_Type::T_LONGTEXT;
+    $queryFields['notes']['type'] = CRM_Utils_Type::T_LONGTEXT;
+    // Set the label to gender for gender_id as we it's ... magic (not in a good way).
+    // In other places the query object offers e.g contribution_status & contribution_status_id
+    $queryFields['gender_id']['title'] = ts('Gender');
     $this->queryFields = $queryFields;
   }
 
@@ -800,7 +806,7 @@ class CRM_Export_BAO_ExportProcessor {
 
     // CRM-13982 - check if is deleted
     foreach ($params as $value) {
-      if ($value[0] == 'contact_is_deleted') {
+      if ($value[0] === 'contact_is_deleted') {
         unset($whereClauses['trash_clause']);
       }
     }
@@ -822,10 +828,10 @@ class CRM_Export_BAO_ExportProcessor {
     }
 
     if (empty($where)) {
-      $where = "WHERE " . implode(' AND ', $whereClauses);
+      $where = 'WHERE ' . implode(' AND ', $whereClauses);
     }
     else {
-      $where .= " AND " . implode(' AND ', $whereClauses);
+      $where .= ' AND ' . implode(' AND ', $whereClauses);
     }
 
     $groupBy = $this->getGroupBy($query);
@@ -870,8 +876,8 @@ class CRM_Export_BAO_ExportProcessor {
     // These oddly constructed keys are for legacy reasons. Altering them will affect test success
     // but in time it may be good to rationalise them.
     $label = $this->getOutputSpecificationLabel($key, $relationshipType, $locationType, $entityLabel);
-    $index = $this->getOutputSpecificationIndex($key, $relationshipType, $locationType, $entityLabel);
-    $fieldKey = $this->getOutputSpecificationFieldKey($key, $relationshipType, $locationType, $entityLabel);
+    $index = $this->getOutputSpecificationIndex($key, $relationshipType, $locationType, $entityTypeID);
+    $fieldKey = $this->getOutputSpecificationFieldKey($key, $relationshipType, $locationType, $entityTypeID);
 
     $this->outputSpecification[$index]['header'] = $label;
     $this->outputSpecification[$index]['sql_columns'] = $this->getSqlColumnDefinition($fieldKey, $key);
@@ -961,18 +967,16 @@ class CRM_Export_BAO_ExportProcessor {
    * @param \CRM_Contact_BAO_Query $query
    * @param CRM_Core_DAO $iterationDAO
    * @param array $outputColumns
-   * @param $metadata
    * @param $paymentDetails
    * @param $addPaymentHeader
    *
    * @return array|bool
    */
-  public function buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader) {
+  public function buildRow($query, $iterationDAO, $outputColumns, $paymentDetails, $addPaymentHeader) {
     $paymentTableId = $this->getPaymentTableID();
     if ($this->isHouseholdToSkip($iterationDAO->contact_id)) {
       return FALSE;
     }
-    $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
     $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
 
     $row = [];
@@ -1003,10 +1007,7 @@ class CRM_Export_BAO_ExportProcessor {
       if (property_exists($iterationDAO, $field)) {
         $fieldValue = $iterationDAO->$field;
         // to get phone type from phone type id
-        if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
-          $fieldValue = $phoneTypes[$fieldValue];
-        }
-        elseif ($field == 'provider_id' || $field == 'im_provider') {
+        if ($field == 'provider_id' || $field == 'im_provider') {
           $fieldValue = $imProviders[$fieldValue] ?? NULL;
         }
         elseif (strstr($field, 'master_id')) {
@@ -1021,7 +1022,7 @@ class CRM_Export_BAO_ExportProcessor {
         $this->buildRelationshipFieldsForRow($row, $iterationDAO->contact_id, $value, $field);
       }
       else {
-        $row[$field] = $this->getTransformedFieldValue($field, $iterationDAO, $fieldValue, $metadata, $paymentDetails);
+        $row[$field] = $this->getTransformedFieldValue($field, $iterationDAO, $fieldValue, $paymentDetails);
       }
     }
 
@@ -1083,12 +1084,13 @@ class CRM_Export_BAO_ExportProcessor {
    * @param $field
    * @param $iterationDAO
    * @param $fieldValue
-   * @param $metadata
    * @param $paymentDetails
    *
    * @return string
+   * @throws \CRM_Core_Exception
+   * @throws \CiviCRM_API3_Exception
    */
-  public function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $metadata, $paymentDetails) {
+  public function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $paymentDetails) {
 
     $i18n = CRM_Core_I18n::singleton();
     if ($field == 'id') {
@@ -1146,31 +1148,27 @@ class CRM_Export_BAO_ExportProcessor {
             return $i18n->crm_translate($fieldValue);
 
           default:
-            $fieldSpec = $metadata[$field] ?? [];
+            $fieldSpec = $this->outputSpecification[$this->getMungedFieldName($field)]['metadata'];
             // No I don't know why we do it this way & whether we could
             // make better use of pseudoConstants.
             if (!empty($fieldSpec['context'])) {
               return $i18n->crm_translate($fieldValue, $fieldSpec);
             }
-            if (!empty($fieldSpec['pseudoconstant'])) {
+            if (!empty($fieldSpec['pseudoconstant']) && !empty($fieldSpec['hasLocationType']) && $fieldSpec['name'] !== 'phone_type_id') {
               if (!empty($fieldSpec['bao'])) {
-                return CRM_Core_PseudoConstant::getLabel($fieldSpec['bao'], $fieldSpec['name'], $fieldValue);
+                $transformedValue = CRM_Core_PseudoConstant::getLabel($fieldSpec['bao'], $fieldSpec['name'], $fieldValue);
+                if ($transformedValue) {
+                  return $transformedValue;
+                }
+                return $fieldValue;
               }
-              // This is not our normal syntax for pseudoconstants but I am a bit loath to
-              // call an external function until sure it is not increasing php processing given this
-              // may be iterated 100,000 times & we already have the $imProvider var loaded.
-              // That can be next refactor...
               // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
               // but I have to reach a stable point....
               $varName = $fieldSpec['pseudoconstant']['var'];
               if ($varName === 'imProviders') {
                 return CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_IM', 'provider_id', $fieldValue);
               }
-              if ($varName === 'phoneTypes') {
-                return CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_Phone', 'phone_type_id', $fieldValue);
-              }
             }
-
             return $fieldValue;
         }
       }
@@ -1436,21 +1434,20 @@ class CRM_Export_BAO_ExportProcessor {
   public function getSqlColumnDefinition($fieldName, $columnName) {
 
     // early exit for master_id, CRM-12100
-    // in the DB it is an ID, but in the export, we retrive the display_name of the master record
-    // also for current_employer, CRM-16939
-    if ($columnName == 'master_id' || $columnName == 'current_employer') {
+    // in the DB it is an ID, but in the export, we retrieve the display_name of the master record
+    if ($columnName === 'master_id') {
       return "`$fieldName` varchar(128)";
     }
 
     $queryFields = $this->getQueryFields();
-    // @todo remove the enotice avoidance here, ensure all columns are declared.
+    // @todo remove the e-notice avoidance here, ensure all columns are declared.
     // tests will fail on the enotices until they all are & then all the 'else'
     // below can go.
     $fieldSpec = $queryFields[$columnName] ?? [];
-
+    $type = $fieldSpec['type'] ?? ($fieldSpec['data_type'] ?? '');
     // set the sql columns
-    if (isset($fieldSpec['type'])) {
-      switch ($fieldSpec['type']) {
+    if ($type) {
+      switch ($type) {
         case CRM_Utils_Type::T_INT:
         case CRM_Utils_Type::T_BOOLEAN:
           if (in_array(CRM_Utils_Array::value('data_type', $fieldSpec), ['Country', 'StateProvince', 'ContactReference'])) {
@@ -1493,39 +1490,28 @@ class CRM_Export_BAO_ExportProcessor {
         return "`$fieldName` text";
       }
       else {
-        $changeFields = [
-          'groups',
-          'tags',
-          'notes',
-        ];
-
-        if (in_array($fieldName, $changeFields)) {
-          return "`$fieldName` text";
-        }
-        else {
-          // set the sql columns for custom data
-          if (isset($queryFields[$columnName]['data_type'])) {
+        // set the sql columns for custom data
+        if (isset($queryFields[$columnName]['data_type'])) {
 
-            switch ($queryFields[$columnName]['data_type']) {
-              case 'String':
-                // May be option labels, which could be up to 512 characters
-                $length = max(512, CRM_Utils_Array::value('text_length', $queryFields[$columnName]));
-                return "`$fieldName` varchar($length)";
+          switch ($queryFields[$columnName]['data_type']) {
+            case 'String':
+              // May be option labels, which could be up to 512 characters
+              $length = max(512, CRM_Utils_Array::value('text_length', $queryFields[$columnName]));
+              return "`$fieldName` varchar($length)";
 
-              case 'Link':
-                return "`$fieldName` varchar(255)";
+            case 'Link':
+              return "`$fieldName` varchar(255)";
 
-              case 'Memo':
-                return "`$fieldName` text";
+            case 'Memo':
+              return "`$fieldName` text";
 
-              default:
-                return "`$fieldName` varchar(255)";
-            }
-          }
-          else {
-            return "`$fieldName` text";
+            default:
+              return "`$fieldName` varchar(255)";
           }
         }
+        else {
+          return "`$fieldName` text";
+        }
       }
     }
   }
@@ -1692,7 +1678,7 @@ class CRM_Export_BAO_ExportProcessor {
    *       yet find a way to comment them for posterity.
    */
   public function getExportStructureArrays() {
-    $outputColumns = $metadata = [];
+    $outputColumns = [];
     $queryFields = $this->getQueryFields();
     foreach ($this->getReturnProperties() as $key => $value) {
       if (($key != 'location' || !is_array($value)) && !$this->isRelationshipTypeKey($key)) {
@@ -1729,13 +1715,12 @@ class CRM_Export_BAO_ExportProcessor {
               $daoFieldName .= "-" . $type[1];
             }
             $this->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array::value(1, $type));
-            $metadata[$daoFieldName] = $this->getMetaDataForField($actualDBFieldName);
             $outputColumns[$daoFieldName] = TRUE;
           }
         }
       }
     }
-    return [$outputColumns, $metadata];
+    return [$outputColumns];
   }
 
   /**
@@ -2070,13 +2055,13 @@ WHERE  id IN ( $deleteIDString )
    */
   public function getPreview($limit) {
     $rows = [];
-    list($outputColumns, $metadata) = $this->getExportStructureArrays();
+    list($outputColumns) = $this->getExportStructureArrays();
     $query = $this->runQuery([], '');
     CRM_Core_DAO::disableFullGroupByMode();
     $result = CRM_Core_DAO::executeQuery($query[1] . ' LIMIT ' . (int) $limit);
     CRM_Core_DAO::reenableFullGroupByMode();
     while ($result->fetch()) {
-      $rows[] = $this->buildRow($query[0], $result, $outputColumns, $metadata, [], []);
+      $rows[] = $this->buildRow($query[0], $result, $outputColumns, [], []);
     }
     return $rows;
   }
@@ -2176,10 +2161,7 @@ WHERE  id IN ( $deleteIDString )
     foreach ($value as $relationField => $relationValue) {
       if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
         $fieldValue = $relDAO->$relationField;
-        if ($relationField == 'phone_type_id') {
-          $fieldValue = $phoneTypes[$relationValue];
-        }
-        elseif ($relationField == 'provider_id') {
+        if ($relationField == 'provider_id') {
           $fieldValue = $imProviders[$relationValue] ?? NULL;
         }
         // CRM-13995