]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/utils/array_utils.php
Release 6.1.4
[Github/sugarcrm.git] / include / utils / array_utils.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38
39
40 //to_string methods to get strings for values
41
42  // var_export gets rid of the empty values that we use to display None
43  // thishelper function fixes that
44  // *This is no longer the case in php 5. var_export will now preserve empty keys.
45 function var_export_helper($tempArray) {
46                 return var_export($tempArray, true);
47         }
48
49
50
51 //this function is used to overide a value in an array and returns the string code to write
52 function override_value_to_string($array_name, $value_name, $value){
53         $string = "\${$array_name}[". var_export($value_name, true). "] = ";
54         $string .= var_export_helper($value,true);
55         return $string . ";";
56 }
57
58 function add_blank_option($options){
59         if(is_array($options)) {
60                 if(!isset($options['']) && !isset($options['0'])) {
61                 $options = array_merge(array(''=>''), $options);
62                 }
63         } else {
64                 $options = array(''=>'');
65         }
66         return $options;
67 }
68
69 /*
70  * Given an array and key names, return a string in the form of $array_name[$key_name[0]][$key_name[1]]... = $value recursively.
71  * @params : $key_names - array of keys
72  *                       $array_name- name of the array
73  *                       $value -value of the array
74  *                       $eval - evals the generated string if true, note that the array name must be in the global space!
75  * @return : example - string $array_name['a']['b']['c'][.] = 'hello'
76  */
77 function override_value_to_string_recursive($key_names, $array_name, $value, $eval=false){
78         if ($eval) return eval( "\${$array_name}". override_recursive_helper($key_names, $array_name, $value));
79         else return "\${$array_name}". override_recursive_helper($key_names, $array_name, $value);
80 }
81
82 function override_recursive_helper($key_names, $array_name, $value){
83         if( empty( $key_names ) )
84                 return "=".var_export_helper($value,true).";";
85         else{
86                 $key = array_shift($key_names);
87                 return "[".var_export($key,true)."]". override_recursive_helper($key_names, $array_name,$value);
88         }
89 }
90
91 function override_value_to_string_recursive2($array_name, $value_name, $value, $save_empty = true) {
92         if (is_array($value)) {
93                 $str = '';
94                 $newArrayName = $array_name . "['$value_name']";
95                 foreach($value as $key=>$val) {
96                         $str.= override_value_to_string_recursive2($newArrayName, $key, $val, $save_empty);
97                 }
98                 return $str;
99         } else {
100                 if(!$save_empty && empty($value)){
101                         return;
102                 }else{
103                         return "\$$array_name" . "['$value_name'] = " . var_export($value, true) . ";\n";
104                 }
105         }
106 }
107
108 /**
109  * This function will attempt to convert an object to an array.
110  * Loops are not checked for so this function should be used with caution.
111  * 
112  * @param $obj
113  * @return array representation of $obj
114  */
115 function object_to_array_recursive($obj)
116 {
117         if (!is_object($obj))
118            return $obj;
119
120         $ret = get_object_vars($obj);
121         foreach($ret as $key => $val)
122         {
123                 if (is_object($val)) {
124                         $ret[$key] = object_to_array_recursive($val);
125                 }
126                 
127         }
128         return $ret;
129 }
130 /**
131          * This function returns an array of all the key=>value pairs in $array1 
132          * that are wither not present, or different in $array2.
133          * If a key exists in $array2 but not $array1, it will not be reported.
134          * Values which are arrays are traced further and reported only if thier is a difference
135          * in one or more of thier children.
136          * 
137          * @param array $array1, the array which contains all the key=>values you wish to check againts
138          * @param array $array2, the array which 
139          * @param array $allowEmpty, will return the value if it is empty in $array1 and not in $array2,
140          * otherwise empty values in $array1 are ignored.
141          * @return array containing the differences between the two arrays
142          */
143         function deepArrayDiff($array1, $array2, $allowEmpty = false) {
144                 $diff = array();
145                 foreach($array1 as $key=>$value) {
146                         if (is_array($value)) {
147                                 if ((!isset($array2[$key]) || !is_array($array2[$key])) && (isset($value) || $allowEmpty)) {
148                                         $diff[$key] = $value;
149                                 } else {
150                                         $value = deepArrayDiff($array1[$key], $array2[$key], $allowEmpty);
151                                         if (!empty($value) || $allowEmpty)
152                                                 $diff[$key] = $value;
153                                 }
154                         } else if ((!isset($array2[$key]) || $value != $array2[$key]) && (isset($value) || $allowEmpty)){
155                                 $diff[$key] = $value;
156                         }
157                 }
158                 return $diff;
159         }
160         
161         /**
162          * Recursivly set a value in an array, creating sub arrays as necessary
163          *
164          * @param unknown_type $array
165          * @param unknown_type $key
166          */
167         function setDeepArrayValue(&$array, $key, $value) {
168                 //if _ is at position zero, that is invalid.
169                 if (strrpos($key, "_")) {
170                 list ($key, $remkey) = explode('_', $key, 2);
171                         if (!isset($array[$key]) || !is_array($array[$key])) {
172                                 $array[$key] = array();
173                         }
174                         setDeepArrayValue($array[$key], $remkey, $value);
175                 }
176                 else {
177                         $array[$key] = $value;
178                 }
179         }
180
181
182 // This function iterates through the given arrays and combines the values of each key, to form one array
183 // Returns FALSE if number of elements in the arrays do not match; otherwise, returns merged array
184 // Example: array("a", "b", "c") and array("x", "y", "z") are passed in; array("ax", "by", "cz") is returned
185 function array_merge_values($arr1, $arr2) {
186         if (count($arr1) != count($arr2)) {
187                 return FALSE;
188         }
189
190         for ($i = 0; $i < count($arr1); $i++) {
191                 $arr1[$i] .= $arr2[$i];
192         }
193
194         return $arr1;
195 }
196
197 /**
198  * Search an array for a given value ignorning case sensitivity
199  *
200  * @param unknown_type $key
201  * @param unknown_type $haystack
202  */
203 function array_search_insensitive($key, $haystack)
204 {
205     if(!is_array($haystack))
206         return FALSE;
207
208     $found = FALSE;
209     foreach($haystack as $k => $v)
210     {
211         if(strtolower($v) == strtolower($key))
212         {
213             $found = TRUE;
214             break;
215         }
216     }
217
218     return $found;
219 }
220
221 /**
222  * Wrapper around PHP's ArrayObject class that provides dot-notation recursive searching
223  * for multi-dimensional arrays
224  */
225 class SugarArray extends ArrayObject
226 {
227     /**
228      * Return the value matching $key if exists, otherwise $default value
229      *
230      * This method uses dot notation to look through multi-dimensional arrays
231      *
232      * @param string $key key to look up
233      * @param mixed $default value to return if $key does not exist
234      * @return mixed
235      */
236     public function get($key, $default = null) {
237         return $this->_getFromSource($key, $default);
238     }
239
240     /**
241      * Provided as a convinience method for fetching a value within an existing
242      * array without instantiating a SugarArray
243      *
244      * NOTE: This should only used where refactoring an array into a SugarArray
245      *       is unfeasible.  This operation is more expensive than a direct
246      *       SugarArray as each time it creates and throws away a new instance
247      *
248      * @param array $haystack haystack
249      * @param string $needle needle
250      * @param mixed $default default value to return
251      * @return mixed
252      */
253     static public function staticGet($haystack, $needle, $default = null) {
254         if (empty($haystack)) {
255             return $default;
256         }
257         $array = new self($haystack);
258         return $array->get($needle, $default);
259     }
260
261     private function _getFromSource($key, $default) {
262         if (strpos($key, '.') === false) {
263             return isset($this[$key]) ? $this[$key] : $default;
264         }
265
266         $exploded = explode('.', $key);
267         $current_key = array_shift($exploded);
268         return $this->_getRecursive($this->_getFromSource($current_key, $default), $exploded, $default);
269     }
270
271     private function _getRecursive($raw_config, $children, $default) {
272         if ($raw_config === $default) {
273             return $default;
274         } elseif (count($children) == 0) {
275             return $raw_config;
276         } else {
277             $next_key = array_shift($children);
278             return isset($raw_config[$next_key]) ?
279                 $this->_getRecursive($raw_config[$next_key], $children, $default) :
280                 $default;
281         }
282     }
283 }
284
285 ?>