From 859a7a950748cdfdfb613420dd5c8b93461cc37e Mon Sep 17 00:00:00 2001 From: eileen Date: Tue, 17 May 2016 13:05:23 +1200 Subject: [PATCH] Add tests for Ensure OptionGroup exists fn & fix optionValueExists to accept ID The option_group_id field accepts name or id so use that. Conflicts: CRM/Core/BAO/OptionValue.php p --- CRM/Core/BAO/OptionValue.php | 18 ++++++++++++++++++ tests/phpunit/api/v3/OptionGroupTest.php | 22 ++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/CRM/Core/BAO/OptionValue.php b/CRM/Core/BAO/OptionValue.php index 116bcbca48..e250beb13f 100644 --- a/CRM/Core/BAO/OptionValue.php +++ b/CRM/Core/BAO/OptionValue.php @@ -518,4 +518,22 @@ class CRM_Core_BAO_OptionValue extends CRM_Core_DAO_OptionValue { return $options; } + /** + * Ensure an option value exists. + * + * This function is intended to be called from the upgrade script to ensure + * that an option value exists, without hitting an error if it already exists. + * + * This is sympathetic to sites who might pre-add it. + */ + public static function ensureOptionValueExists($params) { + $existingValues = civicrm_api3('OptionValue', 'get', array( + 'option_group_id' => $params['option_group_id'], + 'name' => $params['name'], + )); + if (!$existingValues['count']) { + civicrm_api3('OptionValue', 'create', $params); + } + } + } diff --git a/tests/phpunit/api/v3/OptionGroupTest.php b/tests/phpunit/api/v3/OptionGroupTest.php index a84e114537..83e34b6084 100644 --- a/tests/phpunit/api/v3/OptionGroupTest.php +++ b/tests/phpunit/api/v3/OptionGroupTest.php @@ -170,4 +170,26 @@ class api_v3_OptionGroupTest extends CiviUnitTestCase { $this->callAPIAndDocument('OptionGroup', 'delete', array('id' => $result['id']), __FUNCTION__, __FILE__); } + /** + * Ensure only one option value exists after calling ensureOptionValueExists. + */ + public function testEnsureOptionGroupExistsExistingValue() { + CRM_Core_BAO_OptionGroup::ensureOptionGroupExists(array('name' => 'participant_role')); + $this->callAPISuccessGetSingle('OptionGroup', array('name' => 'participant_role')); + } + + /** + * Ensure only one option value exists adds a new value. + */ + public function testEnsureOptionGroupExistsNewValue() { + $optionGroupID = CRM_Core_BAO_OptionGroup::ensureOptionGroupExists(array( + 'name' => 'Bombed', + 'title' => ts('Catastrophy'), + 'description' => ts('blah blah'), + 'is_reserved' => 1, + )); + $optionGroup = $this->callAPISuccessGetSingle('OptionGroup', array('name' => 'Bombed')); + $this->assertEquals($optionGroupID, $optionGroup['id']); + } + } -- 2.25.1