From 3686ffefbe2b80c1b3da2ceae48e08efe1c40182 Mon Sep 17 00:00:00 2001 From: colemanw Date: Wed, 14 Jun 2023 12:39:35 -0400 Subject: [PATCH] Tests - Fix Api4TestTrait to create an option value if needed --- CRM/Core/DAO/AllCoreTables.php | 4 ++-- Civi/Test/Api4TestTrait.php | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/CRM/Core/DAO/AllCoreTables.php b/CRM/Core/DAO/AllCoreTables.php index aeda2885b4..f25bac3e93 100644 --- a/CRM/Core/DAO/AllCoreTables.php +++ b/CRM/Core/DAO/AllCoreTables.php @@ -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; } /** diff --git a/Civi/Test/Api4TestTrait.php b/Civi/Test/Api4TestTrait.php index 4e5cf31e69..88d52ce210 100644 --- a/Civi/Test/Api4TestTrait.php +++ b/Civi/Test/Api4TestTrait.php @@ -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. * -- 2.25.1