Merge pull request #2171 from lcdservices/CRM-13909
[civicrm-core.git] / tests / phpunit / CRM / Utils / ArrayTest.php
1 <?php
2 require_once 'CiviTest/CiviUnitTestCase.php';
3 class CRM_Utils_ArrayTest extends CiviUnitTestCase {
4 function testBreakReference() {
5 // Get a reference and make a change
6 $fooRef1 = self::returnByReference();
7 $this->assertEquals('original', $fooRef1['foo']);
8 $fooRef1['foo'] = 'modified';
9
10 // Make sure that the referenced item was actually changed
11 $fooRef2 = self::returnByReference();
12 $this->assertEquals('modified', $fooRef1['foo']);
13 $this->assertEquals('original', $fooRef2['foo']);
14
15 // Get a non-reference, make a change, and make sure the references were unaffected.
16 $fooNonReference = CRM_Utils_Array::breakReference(self::returnByReference());
17 $fooNonReference['foo'] = 'privately-modified';
18 $this->assertEquals('modified', $fooRef1['foo']);
19 $this->assertEquals('original', $fooRef2['foo']);
20 $this->assertEquals('privately-modified', $fooNonReference['foo']);
21 }
22
23 private function &returnByReference() {
24 static $foo;
25 if ($foo === NULL) {
26 $foo['foo'] = 'original';
27 }
28 return $foo;
29 }
30
31 function testIndexArray() {
32 $inputs = array();
33 $inputs[] = array(
34 'lang' => 'en',
35 'msgid' => 'greeting',
36 'familiar' => false,
37 'value' => 'Hello'
38 );
39 $inputs[] = array(
40 'lang' => 'en',
41 'msgid' => 'parting',
42 'value' => 'Goodbye'
43 );
44 $inputs[] = array(
45 'lang' => 'fr',
46 'msgid' => 'greeting',
47 'value' => 'Bon jour'
48 );
49 $inputs[] = array(
50 'lang' => 'fr',
51 'msgid' => 'parting',
52 'value' => 'Au revoir'
53 );
54 $inputs[] = array(
55 'lang' => 'en',
56 'msgid' => 'greeting',
57 'familiar' => true,
58 'value' => 'Hey'
59 );
60
61 $byLangMsgid = CRM_Utils_Array::index(array('lang', 'msgid'), $inputs);
62 $this->assertEquals($inputs[4], $byLangMsgid['en']['greeting']);
63 $this->assertEquals($inputs[1], $byLangMsgid['en']['parting']);
64 $this->assertEquals($inputs[2], $byLangMsgid['fr']['greeting']);
65 $this->assertEquals($inputs[3], $byLangMsgid['fr']['parting']);
66 }
67
68 function testCollect() {
69 $arr = array(
70 array('catWord' => 'cat', 'dogWord' => 'dog'),
71 array('catWord' => 'chat', 'dogWord' => 'chien'),
72 array('catWord' => 'gato'),
73 );
74 $expected = array('cat', 'chat', 'gato');
75 $this->assertEquals($expected, CRM_Utils_Array::collect('catWord', $arr));
76
77 $arr = array();
78 $arr['en']= (object) array('catWord' => 'cat', 'dogWord' => 'dog');
79 $arr['fr']= (object) array('catWord' => 'chat', 'dogWord' => 'chien');
80 $arr['es']= (object) array('catWord' => 'gato');
81 $expected = array('en' => 'cat', 'fr' => 'chat', 'es' => 'gato');
82 $this->assertEquals($expected, CRM_Utils_Array::collect('catWord', $arr));
83 }
84
85 }