This repository was archived by the owner on Feb 13, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathObjectCreator.php
More file actions
84 lines (75 loc) · 2.01 KB
/
ObjectCreator.php
File metadata and controls
84 lines (75 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
/**
* Dynamic object creator
*
* @author Thiago Delgado Pinto
* @version 0.9.2
*/
class ObjectCreator {
/**
* Create an object from an array. The object will use array's keys as
* public attributes.
*
* WARNING: The generated object will replace sub arrays converting them
* to objects. If you do not want this behaviour, just cast an
* array to an object like this:
*
* $obj = (object) $yourArray;
*
*
* @param array the array map containing the keys and values.
* @param the class name to create on demand (optional).
* @return a object.
*/
static function fromArray(
array $array,
$className = 'stdClass'
) {
$class = self::classDeclaration( $array, $className );
eval( $class );
return new $className;
}
/**
* Create a class declaration from the given array and class name.
*
* @param array the array map containing the keys and values.
* @param the class name.
* @return string.
*/
static function classDeclaration( array $array, $className ) {
function serializeValue( $value ) {
$type = gettype( $value );
if ( 'string' == $type ) { return '"' . $value . '"'; }
if ( 'integer' == $type || 'double' == $type ) { return $value; }
if ( 'boolean' == $type ) { return $value ? 'true' : 'false'; }
if ( 'array' == $type && ((array) $value) === $value ) {
$str = '';
foreach ( $value as $k => $v ) {
$str .= ( '' == $str ) ? 'array( ' : ', ';
if ( is_numeric( $k ) ) {
$str .= " '$k' => " . serializeValue( $v );
} else {
$str .= " $k => " . serializeValue( $v );
}
}
$str .= ' )';
return $str;
}
return '';
}
function attr( $value ) {
return ' = ' . serializeValue( $value );
}
$class = "class $className { \n";
foreach ( $array as $key => $value ) {
if ( is_numeric( $key ) ) {
$class .= "public \$unknown${key}" . attr( $value ) . ";\n";
} else {
$class .= "public \$$key" . attr( $value ) . ";\n";
}
}
$class .= "\n}";
return $class;
}
}
?>