1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Helper class |
4
|
|
|
*/ |
5
|
|
|
|
6
|
|
|
namespace IBM\Watson\Common; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Helper class |
10
|
|
|
* |
11
|
|
|
* This class defines various static utility functions that are used |
12
|
|
|
* throughout the Watson system |
13
|
|
|
*/ |
14
|
|
|
class Helper |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* Convert string to camelCase. Strings already in camelCase will not be affected. |
18
|
|
|
* @param string $str Input string |
19
|
|
|
* @return string camelCased output string |
20
|
|
|
*/ |
21
|
18 |
|
public static function camelCase($str) |
22
|
|
|
{ |
23
|
18 |
|
$str = self::convertToLowercase($str); |
24
|
18 |
|
return preg_replace_callback( |
25
|
18 |
|
'/_([a-z])/', |
26
|
18 |
|
function ($match) { |
27
|
6 |
|
return strtoupper($match[1]); |
28
|
18 |
|
}, |
29
|
|
|
$str |
30
|
12 |
|
); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Initialize an object with given array of parameters |
35
|
|
|
* |
36
|
|
|
* @param mixed $target The object to set parameters on |
37
|
|
|
* @param array $parameters An array of parametes to set |
38
|
|
|
*/ |
39
|
57 |
|
public static function initialize($target, $parameters) |
40
|
|
|
{ |
41
|
57 |
|
if (is_array($parameters)) { |
42
|
51 |
|
foreach ($parameters as $key => $value) { |
43
|
9 |
|
$method = 'set'.ucfirst(static::camelCase($key)); |
44
|
9 |
|
if (method_exists($target, $method)) { |
45
|
9 |
|
$target->$method($value); |
46
|
6 |
|
} |
47
|
34 |
|
} |
48
|
34 |
|
} |
49
|
57 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Convert strings with underscore to be all lowercase before camelCase is performed. |
53
|
|
|
* @param string $str Input string |
54
|
|
|
* @return string Output string |
55
|
|
|
*/ |
56
|
18 |
|
protected static function convertToLowercase($str) |
57
|
|
|
{ |
58
|
18 |
|
$explodedStr = explode('_', $str); |
59
|
|
|
|
60
|
18 |
|
if (count($explodedStr) > 1) { |
61
|
6 |
|
foreach ($explodedStr as $value) { |
62
|
6 |
|
$lowercasedStr[] = strtolower($value); |
|
|
|
|
63
|
4 |
|
} |
64
|
6 |
|
$str = implode('_', $lowercasedStr); |
|
|
|
|
65
|
4 |
|
} |
66
|
|
|
|
67
|
18 |
|
return $str; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.
Let’s take a look at an example:
As you can see in this example, the array
$myArray
is initialized the first time when the foreach loop is entered. You can also see that the value of thebar
key is only written conditionally; thus, its value might result from a previous iteration.This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.