1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Helper class |
4
|
|
|
*/ |
5
|
|
|
namespace IBM\Watson\Common; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Helper class |
9
|
|
|
* |
10
|
|
|
* This class defines various static utility functions that are in use |
11
|
|
|
* throughout the SDK |
12
|
|
|
* |
13
|
|
|
*/ |
14
|
|
|
class Helper |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* Convert a string to camelCase. Strings already in camelCase will not be modified |
18
|
|
|
* |
19
|
|
|
* @param string $string The input string |
20
|
|
|
* @return string The output string |
21
|
|
|
*/ |
22
|
18 |
|
public static function camelCase($string) |
23
|
|
|
{ |
24
|
18 |
|
$string = self::convertToLowercase($string); |
25
|
18 |
|
return preg_replace_callback( |
26
|
18 |
|
'/_([a-z])/', |
27
|
18 |
|
function ($match) { |
28
|
6 |
|
return strtoupper($match[1]); |
29
|
18 |
|
}, |
30
|
|
|
$string |
31
|
12 |
|
); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Convert strings with underscores to all lowercase |
36
|
|
|
* |
37
|
|
|
* @param string string The input string |
38
|
|
|
* @return string The output string |
39
|
|
|
*/ |
40
|
18 |
|
protected static function convertToLowercase($string) |
41
|
|
|
{ |
42
|
18 |
|
$explodedStr = explode('_', $string); |
43
|
|
|
|
44
|
18 |
|
if (count($explodedStr) > 1) { |
45
|
6 |
|
foreach ($explodedStr as $value) { |
46
|
6 |
|
$lowercasedStr[] = strtolower($value); |
|
|
|
|
47
|
4 |
|
} |
48
|
6 |
|
$string = implode('_', $lowercasedStr); |
|
|
|
|
49
|
4 |
|
} |
50
|
|
|
|
51
|
18 |
|
return $string; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Initialize an object with the given parameters |
56
|
|
|
* |
57
|
|
|
* @param mixed $target The object to set parameters on |
58
|
|
|
* @param array $parameters The parameters to set |
59
|
|
|
*/ |
60
|
42 |
|
public static function initialize($target, $parameters) |
61
|
|
|
{ |
62
|
42 |
|
if (is_array($parameters)) { |
63
|
36 |
|
foreach ($parameters as $key => $value) { |
64
|
9 |
|
$method = 'set'.ucfirst(static::camelCase($key)); |
65
|
9 |
|
if (method_exists($target, $method)) { |
66
|
9 |
|
$target->$method($value); |
67
|
6 |
|
} |
68
|
24 |
|
} |
69
|
24 |
|
} |
70
|
42 |
|
} |
71
|
|
|
} |
72
|
|
|
|
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.