Completed
Branch bootstrap-refactoring (37e127)
by Adam
03:53
created

BuildFactory::getAutowiredProperties()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
ccs 11
cts 11
cp 1
rs 9.2
cc 4
eloc 9
nc 4
nop 1
crap 4
1
<?php
2
3
4
namespace Genesis;
5
6
7
use Genesis\Config\Container;
8
9
10
/**
11
 * @author Adam Bisek <[email protected]>
12
 */
13
class BuildFactory
14
{
15
16
	/**
17
	 * @param Container $container
18
	 * @return Build
19
	 */
20 11
	public function create(Container $container, array $arguments = NULL)
21
	{
22 11
		$class = $container->getClass();
23 11
		if (!class_exists($class, TRUE)) {
24 1
			$this->log(sprintf(
25 1
				"Build class '%s' was not found." . PHP_EOL .
26 1
				"Are you in correct working directory?" . PHP_EOL .
27 1
				"Did you forget add bootstrap.php with class loading into working directory?" . PHP_EOL .
28 1
				"Did you forget to load class %s?", $class, $class), 'red');
29 1
			throw new TerminateException(NULL, 255);
30
		}
31 10
		$build = new $class($container, $arguments);
32 10
		if (!($build instanceof IBuild)) {
33
			throw new Exception("Instance of build does not implements interface IBuild.");
34
		}
35 10
		$this->autowire($build, $container);
36 9
		$build->setup();
37 9
		return $build;
38
	}
39
40
41 10
	protected function autowire(IBuild $build, Container $container)
42
	{
43 10
		foreach ($this->getAutowiredProperties($build) as $property => $service) {
44 10
			if(!$container->hasService($service)){
45 1
				throw new Exception("Cannot found service '$service' to inject into " . get_class($build) . "::$property.");
46
			}
47 9
			$build->$property = $container->getService($service);
48 9
		}
49 9
	}
50
51
52 10
	protected function getAutowiredProperties($class)
53
	{
54 10
		$return = [];
55 10
		$reflectionClass = new \ReflectionClass($class);
56 10
		foreach ($reflectionClass->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
57 10
			$reflectionProp = new \ReflectionProperty($class, $property->getName());
58 10
			$doc = $reflectionProp->getDocComment();
59 10
			if (preg_match('#@inject ?([^\s]*)\s#s', $doc, $matches)) {
60 10
				$return[$property->getName()] = trim($matches[1]) !== '' ? $matches[1] : $property->getName();
61 10
			}
62 10
		}
63 10
		return $return;
64
	}
65
66
67 1
	protected function log($message, $color = NULL, $backgroundColor = NULL)
68
	{
69 1
		echo Cli::getColoredString($message . PHP_EOL, $color, $backgroundColor);
70 1
	}
71
72
}