Passed
Push — master ( 52af70...d3d11c )
by Morris
10:15 queued 11s
created

FunctionInjector::injectFn()   A

Complexity

Conditions 6
Paths 1

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 13
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 24
rs 9.2222
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * @copyright 2020 Christoph Wurst <[email protected]>
7
 *
8
 * @author 2020 Christoph Wurst <[email protected]>
9
 *
10
 * @license GNU AGPL version 3 or any later version
11
 *
12
 * This program is free software: you can redistribute it and/or modify
13
 * it under the terms of the GNU Affero General Public License as
14
 * published by the Free Software Foundation, either version 3 of the
15
 * License, or (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU Affero General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License
23
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
24
 */
25
26
namespace OC\AppFramework\Bootstrap;
27
28
use Closure;
29
use OCP\AppFramework\QueryException;
30
use OCP\IContainer;
31
use ReflectionFunction;
32
use ReflectionParameter;
33
use function array_map;
34
35
class FunctionInjector {
36
37
	/** @var IContainer */
38
	private $container;
39
40
	public function __construct(IContainer $container) {
41
		$this->container = $container;
42
	}
43
44
	public function injectFn(callable $fn) {
45
		$reflected = new ReflectionFunction(Closure::fromCallable($fn));
46
		return $fn(...array_map(function (ReflectionParameter $param) {
47
			// First we try by type (more likely these days)
48
			if (($type = $param->getType()) !== null) {
49
				try {
50
					return $this->container->query($type->getName());
51
				} catch (QueryException $ex) {
52
					// Ignore and try name as well
53
				}
54
			}
55
			// Second we try by name (mostly for primitives)
56
			try {
57
				return $this->container->query($param->getName());
58
			} catch (QueryException $ex) {
59
				// As a last resort we pass `null` if allowed
60
				if ($type !== null && $type->allowsNull()) {
61
					return null;
62
				}
63
64
				// Nothing worked, time to bail out
65
				throw $ex;
66
			}
67
		}, $reflected->getParameters()));
68
	}
69
}
70