@@ -29,15 +29,14 @@ final class Instantiator
29
29
* For example:
30
30
*
31
31
* // creates an empty instance of Foo
32
- * Instantiator::instantiate([ Foo::class => []] );
32
+ * Instantiator::instantiate(Foo::class);
33
33
*
34
- * // creates a Foo instance and sets one of its public, protected or private properties
35
- * Instantiator::instantiate([ Foo::class => ['propertyName' => $propertyValue] ]);
34
+ * // creates a Foo instance and sets one of its properties
35
+ * Instantiator::instantiate(Foo::class, ['propertyName' => $propertyValue]);
36
36
*
37
37
* // creates a Foo instance and sets a private property defined on its parent Bar class
38
- * Instantiator::instantiate([
39
- * Foo::class => [],
40
- * Bar::class => ['privatePropertyName' => $propertyValue],
38
+ * Instantiator::instantiate(Foo::class, [], [
39
+ * Bar::class => ['privateBarProperty' => $propertyValue],
41
40
* ]);
42
41
*
43
42
* Instances of ArrayObject, ArrayIterator and SplObjectHash can be created
@@ -49,24 +48,17 @@ final class Instantiator
49
48
* // creates an ArrayObject populated with $inputArray
50
49
* Instantiator::instantiate([ArrayObject::class => ["\0" => $inputArray]]);
51
50
*
52
- * @param array $propertiesByClass The properties to set on the object, keyed by the class to bind to
53
- * when setting them. The first key of the array defines the class
54
- * of the returned instance.
51
+ * @param string $class The class of the instance to create
52
+ * @param array $properties The properties to set on the instance
53
+ * @param array $privateProperties The private properties to set on the instance,
54
+ * keyed by their declaring class
55
55
*
56
56
* @return object The created instance
57
57
*
58
58
* @throws ExceptionInterface When the instance cannot be created
59
59
*/
60
- public static function instantiate (array $ propertiesByClass )
60
+ public static function instantiate (string $ class , array $ properties = array (), array $ privateProperties = array () )
61
61
{
62
- if (!$ propertiesByClass ) {
63
- throw new \ReflectionException ('No class provided. ' );
64
- }
65
-
66
- foreach ($ propertiesByClass as $ class => $ properties ) {
67
- break ;
68
- }
69
-
70
62
$ reflector = Registry::$ reflectors [$ class ] ?? Registry::getClassReflector ($ class );
71
63
72
64
if (Registry::$ cloneable [$ class ]) {
@@ -81,9 +73,11 @@ public static function instantiate(array $propertiesByClass)
81
73
$ wrappedInstance = array (unserialize ('O: ' .\strlen ($ class ).':" ' .$ class .'":0:{} ' ));
82
74
}
83
75
84
- $ instance = array ($ instance );
76
+ if ($ properties ) {
77
+ $ privateProperties [$ class ] = isset ($ privateProperties [$ class ]) ? $ properties + $ privateProperties [$ class ] : $ properties ;
78
+ }
85
79
86
- foreach ($ propertiesByClass as $ class => $ properties ) {
80
+ foreach ($ privateProperties as $ class => $ properties ) {
87
81
if (!$ properties ) {
88
82
continue ;
89
83
}
0 commit comments