Add functions.php, copied from phalanx
[hoplite.git] / base / functions.php
1 <?php
2 // Hoplite
3 // Copyright (c) 2011 Blue Static
4 //
5 // This program is free software: you can redistribute it and/or modify it
6 // under the terms of the GNU General Public License as published by the Free
7 // Software Foundation, either version 3 of the License, or any later version.
8 //
9 // This program is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 // more details.
13 //
14 // You should have received a copy of the GNU General Public License along with
15 // this program. If not, see <http://www.gnu.org/licenses/>.
16
17 namespace hoplite\base;
18
19 /*!
20 Iterates over an array and unsets any empty elements in the array. This
21 operates on the parameter itself.
22 */
23 function ArrayStripEmpty(Array & $array)
24 {
25 foreach ($array as $key => $value)
26 if (is_array($array[$key]))
27 ArrayStripEmpty($array[$key]);
28 else if (empty($value))
29 unset($array[$key]);
30 }
31
32 /*!
33 Turns an under_scored string into a CamelCased one. If |$first_char| is
34 TRUE, then the first character will also be capatalized.
35 */
36 function UnderscoreToCamelCase($string, $first_char = TRUE)
37 {
38 if ($first_char)
39 $string[0] = strtoupper($string[0]);
40 return preg_replace_callback('/_([a-z])/',
41 function($c) { return strtoupper($c[1]); },
42 $string);
43 }
44
45 /*!
46 Turns a CamelCase string to an under_scored one.
47 */
48 function CamelCaseToUnderscore($string)
49 {
50 $string = preg_replace('/([A-Z]+)([A-Z][a-z])/','\1_\2',$string);
51 $string = preg_replace('/([a-z])([A-Z])/','\1_\2', $string);
52 return strtolower($string);
53 }
54
55 /*!
56 Creates a random string of length |$length|, or a random length between 20
57 and 100 if NULL.
58 */
59 function Random($length = NULL)
60 {
61 if ($length === NULL)
62 $length = rand(20, 100);
63
64 $string = '';
65 for ($i = 0; $i < $length; $i++) {
66 $type = rand(0, 300);
67 if ($type < 100)
68 $string .= rand(0, 9);
69 else if ($type < 200)
70 $string .= chr(rand(65, 90));
71 else
72 $string .= chr(rand(97, 122));
73 }
74
75 return $string;
76 }