Completed
Pull Request — master (#81)
by
unknown
03:04
created

DIContainer::__construct()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
nc 4
nop 1
1
<?php
2
3
namespace Zewa;
4
5
class DIContainer
6
{
7
    //So.. I'm storing dependencies so they can be retrived for later collection
8
    //without re-instantiating.. we should make this optional some way?
9
10
    /**
11
     * @var array $dependencies
12
     * @var Config $dependencies['Config']
13
     */
14
    private $dependencies = [];
15
    private $callbacks = [];
16
17
    public function __construct(Config $config)
18
    {
19
        $this->dependencies['\Zewa\DIContainer'] = $this;
20
        $this->dependencies['\Zewa\Config'] = $config;
21
        $controllers = $config->get('controllers');
22
        $services = $config->get('services');
23
        if (is_array($controllers)) {
24
            $this->callbacks = array_merge($controllers);
25
        }
26
27
        if (is_array($services)) {
28
            $this->callbacks = array_merge($services);
29
        }
30
    }
31
32
    private function isDependencyLoaded(string $class) : bool
33
    {
34
        if (isset($this->dependencies[$class])) {
35
            return true;
36
        }
37
38
        return false;
39
    }
40
41
    public function resolve($class, $share = false)
42
    {
43
        if ($this->isDependencyLoaded($class)) {
44
            return $this->dependencies[$class];
45
        } elseif (!empty($this->callbacks[$class])) {
46
            $share = $this->callbacks[$class]['share'] === true || $share === true ? true : false;
47
            //pass an instance of $this to the factory for dependency injection on cached classes
48
            $dependency = $this->callbacks[$class]['factory']($this);
49
            if ($share === true) {
50
                $this->dependencies[$class] = $dependency;
51
            }
52
53
            return $dependency;
54
        }
55
56
        // Reflect on the $class
57
        $reflectionClass = new \ReflectionClass($class);
58
59
        // Fetch the constructor (instance of ReflectionMethod)
60
        $constructor = $reflectionClass->getConstructor();
61
62
        // If there is no constructor, there is no
63
        // dependencies, which means that our job is done.
64 View Code Duplication
        if (! $constructor) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
65
            $dependency = new $class;
66
            if ($share === true) {
67
                $this->dependencies[$class] = $dependency;
68
            }
69
70
            return $dependency;
71
        }
72
73
        // Fetch the arguments from the constructor
74
        // (collection of ReflectionParameter instances)
75
        $params = $constructor->getParameters();
76
77
        // If there is a constructor, but no dependencies,
78
        // our job is done.
79 View Code Duplication
        if (count($params) === 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
80
            $dependency = new $class;
81
            if ($share === true) {
82
                $this->dependencies[$class] = $dependency;
83
            }
84
            return $dependency;
85
        }
86
87
        // This is were we store the dependencies
88
        $newInstanceParams = [];
89
90
        // Loop over the constructor arguments
91
        foreach ($params as $param) {
92
            // Here we should perform a bunch of checks, such as:
93
            // isArray(), isCallable(), isDefaultValueAvailable()
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
94
            // isOptional() etc.
95
96
            // For now, we just check to see if the argument is
97
            // a class, so we can instantiate it,
98
            // otherwise we just pass null.
99
            if (is_null($param->getClass())) {
100
                $newInstanceParams[] = null;
101
                continue;
102
            }
103
104
105
            // This is where 'the magic happens'. We resolve each
106
            // of the dependencies, by recursively calling the
107
            // resolve() method.
108
            // At one point, we will reach the bottom of the
109
            // nested dependencies we need in order to instantiate
110
            // the class.
111
            $newInstanceParams[] = $this->resolve(
112
                $param->getClass()->getName()
113
            );
114
        }
115
116
        // Return the reflected class, instantiated with all its
117
        // dependencies (this happens once for all the
118
        // nested dependencies).
119
        $dependency = $reflectionClass->newInstanceArgs(
120
            $newInstanceParams
121
        );
122
123
        if ($share === true) {
124
            $this->dependencies[$class] = $dependency;
125
        }
126
127
        return $dependency;
128
    }
129
}
130