progetto fatto precedentemente adattato al framework creato con il corso
filippo.bertilotti
2024-06-10 7d7d7a336e8674a54292abe992b260d9cd2db192
commit | author | age
15e03a 1 <?php
F 2 declare(strict_types= 1);
3 namespace Framework;
4 use ReflectionClass;
5 use Closure;
6 use ReflectionNamedType;
7 use InvalidArgumentException;
8
9 class Container {
10
11     private array $registry = [];
12
13     public function set(string $name, Closure $value): void {
14         $this->registry[$name] = $value;
15     }
16     public function get(string $class_name): object {
17         if(array_key_exists($class_name, $this->registry)) {
18             return $this->registry[$class_name]();
19         }
20         $reflector = new ReflectionClass($class_name);
21         $contructor = $reflector->getConstructor();
22
23         $dependencies = [];
24         
25         if($contructor === null) {
26             return new $class_name();
27         }
28
29         foreach($contructor->getParameters() as $param) {
30             $type = $param->getType();
31             
32             if($type === null) {
33                 throw new InvalidArgumentException("Constructor parameter '{$param->getName()}' in the $class_name class has no type declaration");
34             }
35
36             if( ! ($type instanceof ReflectionNamedType)) {
37                 throw new InvalidArgumentException("Constructor parameter '{$param->getName()}' in the $class_name class is an invalid type: $type
38                      - only single named type supported");
39             }
40
41             if($type->isBuiltin()) {
42                 throw new InvalidArgumentException("Unable to resolve costructor parameter '{$param->getName()}' of type '$type' in the '$class_name' class");
43             }
44             $dependencies[] = $this->get((string) $type);
45         }
46         
47         return new $class_name(...$dependencies);
48     }
49 }