Skip to content

Commit 05e8cbe

Browse files
committed
creating method: ServiceContainer::hydrate
1 parent d780214 commit 05e8cbe

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/ServiceContainer.php

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,53 @@ public function has(string $id): bool
107107
|| class_exists($id);
108108
}
109109

110+
/**
111+
* @template T
112+
*
113+
* @param T $classOrObject
114+
* @param array $data
115+
*
116+
* @return T
117+
* @throws ContainerException
118+
*
119+
*/
120+
public function hydrate(string|object $classOrObject, array $data = []): mixed
121+
{
122+
try {
123+
$instance = $classOrObject;
124+
125+
if (is_string($instance)) {
126+
$arguments = [];
127+
$reflection = new ReflectionClass($instance);
128+
129+
if ($reflection->hasMethod('__construct')) {
130+
$reflectionMethod = $reflection->getMethod('__construct');
131+
$argumentsMap = [];
132+
133+
foreach ($reflectionMethod->getParameters() as $parameter) {
134+
$reflectionType = $parameter->getType();
135+
136+
$argumentsMap[$parameter->getName()] = [
137+
'type' => $reflectionType->getName(),
138+
'isBuiltin' => $reflectionType->isBuiltin(),
139+
];
140+
}
141+
142+
foreach (array_intersect_key($data, $argumentsMap) as $key => $value) {
143+
$arguments[$key] = !$argumentsMap[$key]['isBuiltin'] ?
144+
$this->hydrate($argumentsMap[$key]['type'], $value ?? []) : $value;
145+
}
146+
}
147+
148+
$instance = $this->get($instance, $arguments);
149+
}
150+
151+
return $instance;
152+
} catch (Exception $e) {
153+
throw new ContainerException('Could not hydrate object', $e->getCode(), $e);
154+
}
155+
}
156+
110157
/**
111158
* @param ReflectionMethod|ReflectionFunction $reflectionMethod
112159
* @param array $arguments

0 commit comments

Comments
 (0)