Passed
Push — main ( 9f095f...31373f )
by Sammy
01:22
created

ReflectionFactory::make()   A

Complexity

Conditions 5
Paths 20

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 27
rs 9.3888
cc 5
nc 20
nop 3
1
<?php
2
3
namespace HexMakina\LeMarchand;
4
5
class ReflectionFactory
6
{
7
  public static function make($class, $construction_args = [], $container){
8
    try {
9
        $rc = new \ReflectionClass($class);
10
        $instance = null;
11
12
        if (!is_null($constructor = $rc->getConstructor())) {
13
            $construction_args = self::getConstructorParameters($constructor, $construction_args, $container);
14
15
            if ($constructor->isPrivate()) { // singleton ?
16
              // first argument is the static instance-making method
17
                $singleton_method = $rc->getMethod(array_shift($construction_args));
18
                // invoke the method with remaining constructor args
19
                $instance = $container->resolved($class, $singleton_method->invoke(null, $construction_args));
20
            } else {
21
                $instance = $rc->newInstanceArgs($construction_args);
22
            }
23
        } else {
24
            $instance = $rc->newInstanceArgs();
25
        }
26
27
        if ($rc->hasMethod('set_container')) {
28
            $instance->set_container($container);
29
        }
30
        return $instance;
31
32
    } catch (\ReflectionException $e) {
33
        throw new ContainerException($e->getMessage());
34
    }
35
  }
36
37
  private static function getConstructorParameters(\ReflectionMethod $constructor, $construction_args = [], $container)
38
  {
39
      if (empty($construction_args)) {
40
          foreach ($constructor->getParameters() as $param) {
41
              if ($param->getType()) {
42
                  $construction_args [] = $container->get($param->getType()->getName());
0 ignored issues
show
Bug introduced by
The method getName() does not exist on ReflectionType. It seems like you code against a sub-type of ReflectionType such as ReflectionNamedType. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

42
                  $construction_args [] = $container->get($param->getType()->/** @scrutinizer ignore-call */ getName());
Loading history...
43
              } else {
44
                  $setting = 'settings.Constructor.' . $constructor->class . '.' . $param->getName();
45
                  $construction_args [] = $container->getSettings($setting);
46
              }
47
          }
48
      }
49
      return $construction_args;
50
  }
51
}
52