GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( 9c6611...9955fc )
by Dangerous
14:22 queued 01:10
created

DiMaria::setRules()   C

Complexity

Conditions 11
Paths 16

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 28
rs 5.2653
cc 11
eloc 16
nc 16
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace DD;
3
4
/**
5
 * Dependency injector
6
 */
7
class DiMaria
8
{
9
    protected $aliases = [];
10
    protected $cache = [];
11
    protected $injections = [];
12
    protected $params = [];
13
    protected $shared = [];
14
    protected $sharedInstance = [];
15
16
    /**
17
     * Set multiple di rules at once. Rules are applied in the following format:
18
     * [  'aliases' => ['aliasName' => ['instance', ['optional key/value array of params']]],
19
     *    'params' => ['instance' => ['key/value array of params']],
20
     *    'shared' => ['instance' => true],
21
     *    'injections' => ['instance' => [['method', ['key/value array of params']]]
22
     * ]
23
     *
24
     * @param array $rules a multi-dimensional array of rules to set
25
     * @return self
26
     */
27
    public function setRules(array $rules): self
28
    {
29
        if (isset($rules['aliases'])) {
30
            foreach ($rules['aliases'] as $alias => $aliasConfig) {
31
                $this->setAlias($alias, ...$aliasConfig);
32
            }
33
        }
34
        if (isset($rules['params'])) {
35
            foreach ($rules['params'] as $instance => $params) {
36
                $this->setParams($instance, $params);
37
            }
38
        }
39
        if (isset($rules['shared'])) {
40
            foreach ($rules['shared'] as $instance => $isShared) {
41
                if ($isShared) {
42
                    $this->setShared($instance);
43
                }
44
            }
45
        }
46
        if (isset($rules['injections'])) {
47
            foreach ($rules['injections'] as $instance => $config) {
48
                foreach ($config as $params) {
49
                    $this->setInjection($instance, ...$params);
50
                }
51
            }
52
        }
53
        return $this;
54
    }
55
56
    /**
57
     * Alias a class/interface/alias to another.
58
     * @param string $alias     the name of the alias
59
     * @param string $className the name of the class
60
     * @param array  $params    a key/value array of parameter names and values
61
     * @return self
62
     */
63
    public function setAlias(string $alias, string $className, array $params = []): self
64
    {
65
        $this->aliases[$alias] = [
66
            'className' => $className,
67
            'params' => $params
68
        ];
69
        return $this;
70
    }
71
72
    /**
73
     * Call a method after constructing a class
74
     * @param string $className the name of the class
75
     * @param string $method    the name of the method
76
     * @param array  $params    a key/value array of parameter names and values
77
     * @return self
78
     */
79
    public function setInjection(string $className, string $method, array $params = []): self
80
    {
81
        if (! isset($this->injections[$className])) {
82
            $this->injections[$className] = [];
83
        }
84
        if (! isset($this->injections[$className][$method])) {
85
            $this->injections[$className][$method] = [];
86
        }
87
        $this->injections[$className][$method][] = $params;
88
        return $this;
89
    }
90
91
    /**
92
     * Set parameters of a class
93
     * @param string $className the name of the class
94
     * @param array  $params    a key/value array of parameter names and values
95
     * @return self
96
     */
97
    public function setParams(string $className, array $params): self
98
    {
99
        $this->params[$className] = $params + ($this->params[$className] ?? []);
100
        return $this;
101
    }
102
103
    /**
104
     * Mark a class/alias as shared
105
     * @param string $className the name of class/alias
106
     * @return self
107
     */
108
    public function setShared(string $className): self
109
    {
110
        $this->shared[$className] = true;
111
        return $this;
112
    }
113
114
    /**
115
     * Get an instance of a class
116
     * @param  string $className the name of class/alias to create
117
     * @param  array $params     a key/value array of parameter names and values
118
     * @return mixed             an instance of the class requested
119
     */
120
    public function get(string $className, array $params = [])
121
    {
122
        if (isset($this->shared[$className]) && isset($this->sharedInstance[$className])) {
123
            return $this->sharedInstance[$className];
124
        }
125
        $originalClassName = $className;
126
        while ($alias = $this->aliases[$className] ?? false) {
127
            $params = $params + $alias['params'];
128
            $className = $alias['className'];
129
        }
130
        $callback = $this->cache[$originalClassName] ?? $this->getCallback($className, $originalClassName);
131
        $object = $callback($params);
132
        if (isset($this->shared[$originalClassName])) {
133
            $this->sharedInstance[$originalClassName] = $object;
134
        }
135
        return $object;
136
    }
137
138
    protected function getCallback(string $className, string $originalClassName): callable
139
    {
140
        $callback = $this->generateCallback($className);
141
        if (isset($this->injections[$originalClassName])) {
142
            foreach ($this->injections[$originalClassName] as $method => $instance) {
143
                $methodInfo = $this->getMethodInfo(new \ReflectionMethod($className, $method));
144
                foreach ($instance as $methodParameters) {
145
                    $methodParams = $this->getParameters($methodInfo, $methodParameters);
146
                    $callback = function ($params) use ($callback, $method, $methodParams) {
147
                        $object = $callback($params);
148
                        $object->$method(...$methodParams);
149
                        return $object;
150
                    };
151
                };
152
            }
153
        }
154
        $this->cache[$originalClassName] = $callback;
155
        return $callback;
156
    }
157
158
    protected function generateCallback(string $className): callable
159
    {
160
        $constructor = (new \ReflectionClass($className))->getConstructor();
161
162
        if (! $constructor || ! $constructor->getNumberOfParameters()) {
163
            return function () use ($className) {
164
                return new $className;
165
            };
166
        }
167
        $constructorInfo = $this->getMethodInfo($constructor);
168
        $predefinedParams = $this->params[$className] ?? [];
169
        return function ($params) use ($className, $constructorInfo, $predefinedParams) {
170
            return new $className(...$this->getParameters($constructorInfo, $params + $predefinedParams));
171
        };
172
    }
173
174
    protected function getMethodInfo(\ReflectionMethod $method): array
175
    {
176
        $paramInfo = [];
177
        foreach ($method->getParameters() as $param) {
178
            $paramType = $param->hasType() ? $param->getType() : null;
179
            $paramType = $paramType ? $paramType->isBuiltin() ? null : $paramType->__toString() : null;
180
            $paramInfo[$param->name] = [
181
                'name' => $param->name,
182
                'optional' => $param->isOptional(),
183
                'default' => $param->isOptional() ? ($param->isVariadic() ? null : $param->getDefaultValue()) : null,
184
                'variadic' => $param->isVariadic(),
185
                'type' => $paramType,
186
            ];
187
        }
188
        return $paramInfo;
189
    }
190
191
    protected function getParameters(array $methodInfo, array $params): array
192
    {
193
        $parameters = [];
194
        foreach ($methodInfo as $param) {
195
            if (isset($params[$param['name']])) {
196
                array_push($parameters, ...$this->determineParameter($params[$param['name']], $param['variadic']));
197
            } elseif ($param['optional']) {
198
                if ($param['variadic']) {
199
                    break;
200
                }
201
                $parameters[] = $param['default'];
202
            } elseif ($param['type']) {
203
                $parameters[] = $this->get($param['type']);
204
            } else {
205
                throw new \Exception('Required parameter $' . $param['name'] . ' is missing');
206
            }
207
        }
208
        return $parameters;
209
    }
210
211
    protected function determineParameter($param, bool $isVariadic): array
212
    {
213
        if (is_array($param)) {
214
            if ($isVariadic) {
215
                $params = [];
216
                foreach ($param as $a) {
217
                    $params[] = isset($a['instanceOf']) ? $this->get($a['instanceOf']) : $a;
218
                }
219
                return $params;
220
            }
221
            return isset($param['instanceOf']) ? [$this->get($param['instanceOf'])] : [$param];
222
        }
223
        return [$param];
224
    }
225
}
226