progetto fatto precedentemente adattato al framework creato con il corso
filippo.bertilotti
2024-06-10 86a7fdf7157d24fa53a871956578ab3cd31ed699
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
<?php
declare(strict_types= 1);
namespace Framework;
use ReflectionClass;
use Closure;
use ReflectionNamedType;
use InvalidArgumentException;
 
class Container {
 
    private array $registry = [];
 
    public function set(string $name, Closure $value): void {
        $this->registry[$name] = $value;
    }
    public function get(string $class_name): object {
        if(array_key_exists($class_name, $this->registry)) {
            return $this->registry[$class_name]();
        }
        $reflector = new ReflectionClass($class_name);
        $contructor = $reflector->getConstructor();
 
        $dependencies = [];
        
        if($contructor === null) {
            return new $class_name();
        }
 
        foreach($contructor->getParameters() as $param) {
            $type = $param->getType();
            
            if($type === null) {
                throw new InvalidArgumentException("Constructor parameter '{$param->getName()}' in the $class_name class has no type declaration");
            }
 
            if( ! ($type instanceof ReflectionNamedType)) {
                throw new InvalidArgumentException("Constructor parameter '{$param->getName()}' in the $class_name class is an invalid type: $type
                     - only single named type supported");
            }
 
            if($type->isBuiltin()) {
                throw new InvalidArgumentException("Unable to resolve costructor parameter '{$param->getName()}' of type '$type' in the '$class_name' class");
            }
            $dependencies[] = $this->get((string) $type);
        }
        
        return new $class_name(...$dependencies);
    }
}