Merge pull request #7797 from JKingsnorth/CRM-17977
[civicrm-core.git] / tests / phpunit / api / v3 / CustomValueTest.php
1 <?php
2 /**
3 * +--------------------------------------------------------------------+
4 * | CiviCRM version 4.7 |
5 * +--------------------------------------------------------------------+
6 * | Copyright CiviCRM LLC (c) 2004-2016 |
7 * +--------------------------------------------------------------------+
8 * | This file is a part of CiviCRM. |
9 * | |
10 * | CiviCRM is free software; you can copy, modify, and distribute it |
11 * | under the terms of the GNU Affero General Public License |
12 * | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 * | |
14 * | CiviCRM is distributed in the hope that it will be useful, but |
15 * | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 * | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 * | See the GNU Affero General Public License for more details. |
18 * | |
19 * | You should have received a copy of the GNU Affero General Public |
20 * | License and the CiviCRM Licensing Exception along |
21 * | with this program; if not, contact CiviCRM LLC |
22 * | at info[AT]civicrm[DOT]org. If you have questions about the |
23 * | GNU Affero General Public License or the licensing of CiviCRM, |
24 * | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 * +--------------------------------------------------------------------+
26 */
27
28 /**
29 * Class api_v3_CustomValueTest
30 * @group headless
31 */
32 class api_v3_CustomValueTest extends CiviUnitTestCase {
33 protected $_apiversion = 3;
34 protected $ids;
35 protected $optionGroup;
36
37 public $DBResetRequired = FALSE;
38
39 public function setUp() {
40 parent::setUp();
41 }
42
43 public function _populateOptionAndCustomGroup($type = NULL) {
44 $dataValues = array(
45 'integer' => array(1, 2, 3),
46 'number' => array(10.11, 20.22, 30.33),
47 'string' => array(substr(sha1(rand()), 0, 4), substr(sha1(rand()), 0, 3), substr(sha1(rand()), 0, 2)),
48 // 'country' => array_rand(CRM_Core_PseudoConstant::country(FALSE, FALSE), 3),
49 // This does not work in the test at the moment due to caching issues.
50 //'state_province' => array_rand(CRM_Core_PseudoConstant::stateProvince(FALSE, FALSE), 3),
51 'date' => NULL,
52 'contact' => NULL,
53 'boolean' => NULL,
54 );
55
56 $dataValues = !empty($type) ? array($type => $dataValues[$type]) : $dataValues;
57
58 foreach ($dataValues as $dataType => $values) {
59 $this->optionGroup[$dataType] = array('values' => $values);
60 if (!empty($values)) {
61 $result = $this->callAPISuccess('OptionGroup', 'create',
62 array(
63 'name' => "{$dataType}_group",
64 'api.option_value.create' => array('label' => "$dataType 1", 'value' => $values[0]),
65 'api.option_value.create.1' => array('label' => "$dataType 2", 'value' => $values[1]),
66 'api.option_value.create.2' => array('label' => "$dataType 3", 'value' => $values[2]),
67 )
68 );
69 $this->optionGroup[$dataType]['id'] = $result['id'];
70 }
71 elseif ($dataType == 'contact') {
72 for ($i = 0; $i < 3; $i++) {
73 $result = $this->callAPISuccess('Contact', 'create', array('contact_type' => 'Individual', 'email' => substr(sha1(rand()), 0, 7) . '@yahoo.com'));
74 $this->optionGroup[$dataType]['values'][$i] = $result['id'];
75 }
76 }
77 $this->ids[$dataType] = $this->entityCustomGroupWithSingleFieldCreate("$dataType Custom Group", 'Contacts');
78 }
79
80 }
81
82 public function tearDown() {
83 $tablesToTruncate = array(
84 'civicrm_email',
85 'civicrm_custom_field',
86 'civicrm_custom_group',
87 'civicrm_contact',
88 );
89
90 // true tells quickCleanup to drop any tables that might have been created in the test
91 $this->quickCleanup($tablesToTruncate, TRUE);
92
93 // cleanup created option group for each custom-set before running next test
94 if (!empty($this->optionGroup)) {
95 foreach ($this->optionGroup as $type => $value) {
96 if (!empty($value['id'])) {
97 $this->callAPISuccess('OptionGroup', 'delete', array('id' => $value['id']));
98 }
99 }
100 }
101 }
102
103 public function testCreateCustomValue() {
104 $this->_populateOptionAndCustomGroup();
105
106 $customFieldDataType = CRM_Core_BAO_CustomField::dataType();
107 $dataToHtmlTypes = CRM_Core_BAO_CustomField::dataToHtml();
108 $count = 0;
109 $optionSupportingHTMLTypes = array('Select', 'Radio', 'CheckBox', 'AdvMulti-Select', 'Autocomplete-Select', 'Multi-Select');
110
111 foreach ($customFieldDataType as $dataType => $label) {
112 switch ($dataType) {
113 // case 'Country':
114 // case 'StateProvince':
115 case 'String':
116 case 'Link':
117 case 'Int':
118 case 'Float':
119 case 'Money':
120 case 'Date':
121 case 'Boolean':
122
123 //Based on the custom field data-type choose desired SQL operators(to test with) and basic $type
124 if (in_array($dataType, array('String', 'Link'))) {
125 $validSQLOperators = array('=', '!=', 'IN', 'NOT IN', 'LIKE', 'NOT LIKE', 'IS NOT NULL', 'IS NULL');
126 $type = 'string';
127 }
128 elseif ($dataType == 'Boolean') {
129 $validSQLOperators = array('=', '!=', 'IS NOT NULL', 'IS NULL');
130 $type = 'boolean';
131 }
132 else {
133 if ($dataType == 'Country') {
134 $type = 'country';
135 }
136 elseif ($dataType == 'StateProvince') {
137 $type = 'state_province';
138 }
139 elseif ($dataType == 'ContactReference') {
140 $type = 'contact';
141 }
142 elseif ($dataType == 'Date') {
143 $type = 'date';
144 }
145 else {
146 $type = $dataType == 'Int' ? 'integer' : 'number';
147 }
148 $validSQLOperators = array('=', '!=', 'IN', 'NOT IN', '<=', '>=', '>', '<', 'IS NOT NULL', 'IS NULL');
149 }
150
151 //Create custom field of $dataType and html-type $html
152 foreach ($dataToHtmlTypes[$count] as $html) {
153 // per CRM-18568 the like operator does not currently work for fields with options.
154 // the LIKE operator could potentially bypass ACLs (as could IS NOT NULL) and some thought needs to be given
155 // to it.
156 if (in_array($html, $optionSupportingHTMLTypes)) {
157 $validSQLOperators = array_diff($validSQLOperators, array('LIKE', 'NOT LIKE'));
158 }
159 $params = array(
160 'custom_group_id' => $this->ids[$type]['custom_group_id'],
161 'label' => "$dataType - $html",
162 'data_type' => $dataType,
163 'html_type' => $html,
164 'default_value' => NULL,
165 );
166 if (!in_array($html, array('Text', 'TextArea')) && !in_array($dataType, array('Link', 'Date', 'ContactReference', 'Boolean'))) {
167 $params += array('option_group_id' => $this->optionGroup[$type]['id']);
168 }
169 $customField = $this->customFieldCreate($params);
170 //Now test with $validSQLOperator SQL operators against its custom value(s)
171 $this->_testCustomValue($customField['values'][$customField['id']], $validSQLOperators, $type);
172 }
173 $count++;
174 break;
175
176 default:
177 // skipping File data-type & state province due to caching issues
178 $count++;
179 break;
180 }
181 }
182 }
183
184 public function _testCustomValue($customField, $sqlOps, $type) {
185 $isSerialized = CRM_Core_BAO_CustomField::isSerialized($customField);
186 $customId = $customField['id'];
187 $params = array(
188 'contact_type' => 'Individual',
189 'email' => substr(sha1(rand()), 0, 7) . 'man1@yahoo.com',
190 );
191 $result = $this->callAPISuccess('Contact', 'create', $params);
192 $contactId = $result['id'];
193
194 $count = rand(1, 2);
195
196 if ($isSerialized) {
197 $selectedValue = $this->optionGroup[$type]['values'];
198 $notselectedValue = $selectedValue[$count];
199 unset($selectedValue[$count]);
200 }
201 elseif ($customField['html_type'] == 'Link') {
202 $selectedValue = "http://" . substr(sha1(rand()), 0, 7) . ".com";
203 $notselectedValue = "http://" . substr(sha1(rand()), 0, 7) . ".com";
204 }
205 elseif ($type == 'date') {
206 $selectedValue = date('Ymd');
207 $notselectedValue = $lesserSelectedValue = date('Ymd', strtotime('yesterday'));
208 $greaterSelectedValue = date('Ymd', strtotime('+ 1 day'));
209 }
210 elseif ($type == 'contact') {
211 $selectedValue = $this->optionGroup[$type]['values'][1];
212 $notselectedValue = $this->optionGroup[$type]['values'][0];
213 }
214 elseif ($type == 'boolean') {
215 $selectedValue = 1;
216 $notselectedValue = 0;
217 }
218 else {
219 $selectedValue = $this->optionGroup[$type]['values'][0];
220 $notselectedValue = $this->optionGroup[$type]['values'][$count];
221 if (in_array(">", $sqlOps)) {
222 $greaterSelectedValue = $selectedValue + 1;
223 $lesserSelectedValue = $selectedValue - 1;
224 }
225 }
226
227 $params = array('entity_id' => $contactId, 'custom_' . $customId => $selectedValue);
228 $this->callAPISuccess('CustomValue', 'create', $params);
229
230 foreach ($sqlOps as $op) {
231 $qillOp = CRM_Utils_Array::value($op, CRM_Core_SelectValues::getSearchBuilderOperators(), $op);
232 switch ($op) {
233 case '=':
234 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => (is_array($selectedValue) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $selectedValue) : $selectedValue)));
235 $this->assertEquals($contactId, $result['id']);
236 break;
237
238 case '!=':
239 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => $notselectedValue)));
240 $this->assertEquals(TRUE, array_key_exists($contactId, $result['values']));
241 break;
242
243 case '>':
244 case '<':
245 case '>=':
246 case '<=':
247 if ($isSerialized) {
248 continue;
249 }
250 // To be precise in for these operator we can't just rely on one contact,
251 // hence creating multiple contact with custom value less/more then $selectedValue respectively
252 $result = $this->callAPISuccess('Contact', 'create', array('contact_type' => 'Individual', 'email' => substr(sha1(rand()), 0, 7) . 'man2@yahoo.com'));
253 $contactId2 = $result['id'];
254 $this->callAPISuccess('CustomValue', 'create', array('entity_id' => $contactId2, 'custom_' . $customId => $lesserSelectedValue));
255
256 if ($op == '>') {
257 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => $lesserSelectedValue)));
258 $this->assertEquals($contactId, $result['id']);
259 }
260 elseif ($op == '<') {
261 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => $selectedValue)));
262 $this->assertEquals($contactId2, $result['id']);
263 }
264 else {
265 $result = $this->callAPISuccess('Contact', 'create', array('contact_type' => 'Individual', 'email' => substr(sha1(rand()), 0, 7) . 'man3@yahoo.com'));
266 $contactId3 = $result['id'];
267 $this->callAPISuccess('CustomValue', 'create', array('entity_id' => $contactId3, 'custom_' . $customId => $greaterSelectedValue));
268
269 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => $selectedValue)));
270
271 $this->assertEquals($contactId, $result['values'][$contactId]['id']);
272 if ($op == '>=') {
273 $this->assertEquals($contactId3, $result['values'][$contactId3]['id']);
274 }
275 else {
276 $this->assertEquals($contactId2, $result['values'][$contactId2]['id']);
277 }
278 $this->callAPISuccess('contact', 'delete', array('id' => $contactId3));
279 }
280
281 $this->callAPISuccess('contact', 'delete', array('id' => $contactId2));
282 break;
283
284 case 'IN':
285 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => (array) $selectedValue)));
286 $this->assertEquals($contactId, $result['id']);
287 break;
288
289 case 'NOT IN':
290 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => (array) $notselectedValue)));
291 $this->assertEquals($contactId, $result['id']);
292 break;
293
294 case 'LIKE':
295 $selectedValue = is_array($selectedValue) ? $selectedValue[0] : $selectedValue;
296 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => "%$selectedValue%")));
297 $this->assertEquals($contactId, $result['id']);
298 break;
299
300 case 'NOT LIKE':
301 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => $notselectedValue)));
302 $this->assertEquals($contactId, $result['id']);
303 break;
304
305 case 'IS NULL':
306 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => 1)));
307 $this->assertEquals(FALSE, array_key_exists($contactId, $result['values']));
308 break;
309
310 case 'IS NOT NULL':
311 $result = $this->callAPISuccess('Contact', 'Get', array('custom_' . $customId => array($op => 1)));
312 $this->assertEquals($contactId, $result['id']);
313 break;
314 }
315 }
316
317 $this->callAPISuccess('Contact', 'delete', array('id' => $contactId));
318 }
319
320 /**
321 * Ensure custom data is updated when option values are modified
322 *
323 * @link https://issues.civicrm.org/jira/browse/CRM-11856
324 *
325 * @throws \CiviCRM_API3_Exception
326 */
327 public function testAlterOptionValue() {
328 $this->_populateOptionAndCustomGroup('string');
329
330 $selectField = $this->customFieldCreate(array(
331 'custom_group_id' => $this->ids['string']['custom_group_id'],
332 'label' => 'Custom Select',
333 'html_type' => 'Select',
334 'option_group_id' => $this->optionGroup['string']['id'],
335 ));
336 $selectField = civicrm_api3('customField', 'getsingle', array('id' => $selectField['id']));
337 $radioField = $this->customFieldCreate(array(
338 'custom_group_id' => $this->ids['string']['custom_group_id'],
339 'label' => 'Custom Radio',
340 'html_type' => 'Radio',
341 'option_group_id' => $selectField['option_group_id'],
342 ));
343 $multiSelectField = $this->customFieldCreate(array(
344 'custom_group_id' => $this->ids['string']['custom_group_id'],
345 'label' => 'Custom Multi-Select',
346 'html_type' => 'Multi-Select',
347 'option_group_id' => $selectField['option_group_id'],
348 ));
349 $selectName = 'custom_' . $selectField['id'];
350 $radioName = 'custom_' . $radioField['id'];
351 $multiSelectName = 'custom_' . $multiSelectField['id'];
352 $controlFieldName = 'custom_' . $this->ids['string']['custom_field_id'];
353
354 $params = array(
355 'first_name' => 'abc4',
356 'last_name' => 'xyz4',
357 'contact_type' => 'Individual',
358 'email' => 'man4@yahoo.com',
359 $selectName => $this->optionGroup['string']['values'][0],
360 $multiSelectName => $this->optionGroup['string']['values'],
361 $radioName => $this->optionGroup['string']['values'][1],
362 // The control group in a science experiment should be unaffected
363 $controlFieldName => $this->optionGroup['string']['values'][2],
364 );
365
366 $contact = $this->callAPISuccess('Contact', 'create', $params);
367
368 $result = $this->callAPISuccess('Contact', 'getsingle', array(
369 'id' => $contact['id'],
370 'return' => array($selectName, $multiSelectName),
371 ));
372 $this->assertEquals($params[$selectName], $result[$selectName]);
373 $this->assertEquals($params[$multiSelectName], $result[$multiSelectName]);
374
375 $this->callAPISuccess('OptionValue', 'create', array(
376 'value' => 'one-modified',
377 'option_group_id' => $selectField['option_group_id'],
378 'name' => 'string 1',
379 'options' => array(
380 'match-mandatory' => array('option_group_id', 'name'),
381 ),
382 ));
383
384 $result = $this->callAPISuccess('Contact', 'getsingle', array(
385 'id' => $contact['id'],
386 'return' => array($selectName, $multiSelectName, $controlFieldName, $radioName),
387 ));
388 // Ensure the relevant fields have been updated
389 $this->assertEquals('one-modified', $result[$selectName]);
390 $this->assertEquals(array('one-modified', $params[$radioName], $params[$controlFieldName]), $result[$multiSelectName]);
391 // This field should not have changed because we didn't alter this option
392 $this->assertEquals($params[$radioName], $result[$radioName]);
393 // This should not have changed because this field doesn't use the affected option group
394 $this->assertEquals($params[$controlFieldName], $result[$controlFieldName]);
395 }
396
397 }