Tests - Fix Api4TestTrait to create an option value if needed
authorcolemanw <coleman@civicrm.org>
Wed, 14 Jun 2023 16:39:35 +0000 (12:39 -0400)
committercolemanw <coleman@civicrm.org>
Wed, 14 Jun 2023 16:39:35 +0000 (12:39 -0400)
CRM/Core/DAO/AllCoreTables.php
Civi/Test/Api4TestTrait.php

index aeda2885b40235eae105b13d6519109c696f494a..f25bac3e9338c2a93b875fffabac6026cc61808a 100644 (file)
@@ -309,13 +309,13 @@ class CRM_Core_DAO_AllCoreTables {
    * @param string $tableName
    * @return string|CRM_Core_DAO|NULL
    */
-  public static function getClassForTable($tableName) {
+  public static function getClassForTable(string $tableName) {
     //CRM-19677: on multilingual setup, trim locale from $tableName to fetch class name
     if (CRM_Core_I18n::isMultilingual()) {
       global $dbLocale;
       $tableName = str_replace($dbLocale, '', $tableName);
     }
-    return CRM_Utils_Array::value($tableName, self::tables());
+    return self::tables()[$tableName] ?? NULL;
   }
 
   /**
index 4e5cf31e696878c5bbac4303eff9e4e96648c01c..88d52ce21043693a5bcb8ee4442c8e9fbd0855c7 100644 (file)
@@ -244,6 +244,14 @@ trait Api4TestTrait {
           return $this->getFkID('Contact');
       }
     }
+    // If there are no options but the field is supposed to have them, we may need to
+    // create a new option
+    if (!empty($field['suffixes']) && !empty($field['table_name'])) {
+      $optionValue = $this->createOptionValue($field['table_name'], $field['name']);
+      if ($optionValue) {
+        return $optionValue;
+      }
+    }
 
     $randomValue = $this->getRandomValue($field['data_type']);
 
@@ -254,6 +262,26 @@ trait Api4TestTrait {
     throw new \CRM_Core_Exception('Could not provide default value');
   }
 
+  /**
+   * Creates a dummy option value when one is required but the option list is empty
+   *
+   * @param string $tableName
+   * @param string $fieldName
+   * @return mixed|null
+   */
+  private function createOptionValue(string $tableName, string $fieldName) {
+    $daoName = \CRM_Core_DAO_AllCoreTables::getClassForTable($tableName);
+    $pseudoconstant = $daoName::getSupportedFields()[$fieldName]['pseudoconstant'] ?? NULL;
+    if (!empty($pseudoconstant['optionGroupName'])) {
+      $newOption = $this->createTestRecord('OptionValue', [
+        'option_group_id:name' => $pseudoconstant['optionGroupName'],
+      ]);
+      return $newOption['value'];
+    }
+    // Other types of
+    return NULL;
+  }
+
   /**
    * Delete records previously created by the `saveTestRecords` function.
    *