Completed
Push — master ( dfe763...e059c1 )
by Ron
05:04
created

FileWorker::normalize()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 23
rs 8.5906
cc 6
eloc 16
nc 6
nop 1
1
<?php
2
namespace View\Workers;
3
4
use Exception;
5
use View\Delegates\Delegate;
6
use View\Helpers\Directories;
7
use View\Workers\FileWorker\FileWorkerConfiguration;
8
9
class FileWorker extends AbstractWorker {
10
	/** @var string */
11
	private $currentWorkDir;
12
	/** @var string */
13
	private $fileExt;
14
	/** @var Delegate */
15
	private $parent;
16
17
	/**
18
	 * @param string $basePath
19
	 * @param string $fileExt
20
	 * @param array $vars
21
	 * @param WorkerConfiguration $configuration
22
	 * @param Delegate $parent
23
	 */
24
	public function __construct($basePath, $fileExt = null, array $vars = array(), WorkerConfiguration $configuration = null, Delegate $parent = null) {
25
		if($fileExt === null)  {
26
			$fileExt = '.phtml';
27
		}
28
		if($configuration === null) {
29
			$configuration = new FileWorkerConfiguration();
30
		}
31
		parent::__construct($vars, [], $configuration);
32
		$this->currentWorkDir = $basePath;
33
		$this->fileExt = $fileExt;
34
		$this->parent = $parent;
35
	}
36
37
	/**
38
	 * @param string|callable $resource
39
	 * @param array $vars
40
	 * @throws \Exception
41
	 * @return string
42
	 */
43
	public function render($resource, array $vars = array()) {
44
		$worker = new FileWorker($this->currentWorkDir, $this->fileExt, $this->getVars(), $this->getConfiguration(), $this->parent);
45
		return $worker->getContent($resource, $vars, $this->getRegions());
0 ignored issues
show
Documentation introduced by
$resource is of type callable, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
46
	}
47
48
	/**
49
	 * @param string $resource
50
	 * @param array $vars
51
	 * @param array $regions
52
	 * @return string
53
	 * @throws \Exception
54
	 */
55
	public function getContent($resource, array $vars = array(), array $regions = array()) {
56
		list($oldVars, $oldRegions) = [$this->getVars(), $this->getRegions()];
57
		$subPath = dirname($resource) !== '.' ? dirname($resource) : '';
58
		$filename = basename($resource);
59
		$this->currentWorkDir = Directories::concat($this->currentWorkDir, $subPath);
60
61
		$vars = array_merge($oldVars, $vars);
62
		$regions = array_merge($oldRegions, $regions);
63
		$this->setVars($vars);
64
		$this->setRegions($regions);
65
66
		try {
67
			$content = $this->obRecord(function () use ($filename, $resource, $vars) {
68
				$templateFilename = Directories::concat($this->currentWorkDir, $filename);
69
				$templateFilename = $this->normalize($templateFilename);
70
				$templatePath = stream_resolve_include_path($templateFilename . $this->fileExt);
71
				if($templatePath === false) {
72
					$templatePath = stream_resolve_include_path($templateFilename);
73
				}
74
				if($templatePath !== false) {
75
					$templateFilename = $templatePath;
76
					$fn = function () use ($templateFilename) {
77
						/** @noinspection PhpIncludeInspection */
78
						require $templateFilename;
79
					};
80
					$fn->bindTo(new \stdClass());
81
					call_user_func($fn);
82
				} else {
83
					if($this->parent !== null) {
84
						echo $this->parent->render($resource, $vars);
85
					} else {
86
						throw new Exception("Resource not found: {$resource}");
87
					}
88
				}
89
			});
90
			return $this->generateLayoutContent($content);
91
		} finally {
92
			$this->setVars($oldVars);
93
			$this->setRegions($oldRegions);
0 ignored issues
show
Documentation introduced by
$oldRegions is of type array<integer,object<View\Helpers\StringBucket>>, but the function expects a array<integer,array>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
94
		}
95
	}
96
97
	/**
98
	 * @param string $content
99
	 * @return string
100
	 * @throws \Exception
101
	 */
102
	private function generateLayoutContent($content) {
103
		if($this->getLayout() !== null) {
104
			$regions = $this->getRegions();
105
			$regions['content'] = $content;
106
			$layoutResource = $this->getLayout();
107
			$layoutVars = $this->getLayoutVars();
108
			$worker = new FileWorker($this->currentWorkDir, $this->fileExt, [], $this->getConfiguration(), $this->parent);
109
			$content = $worker->getContent($layoutResource, $layoutVars, $regions);
110
		}
111
		return $content;
112
	}
113
114
	/**
115
	 * @param callback $fn
116
	 * @return string
117
	 * @throws \Exception
118
	 */
119
	private function obRecord($fn) {
120
		try {
121
			ob_start();
122
			call_user_func($fn);
123
			return ob_get_clean();
124
		} catch (Exception $e) {
125
			ob_end_flush();
126
			throw $e;
127
		}
128
	}
129
130
	/**
131
	 * @param string $templateFilename
132
	 * @return string
133
	 */
134
	private function normalize($templateFilename) {
135
		if(strpos($templateFilename, '..')) {
136
			$templateFilename = strtr($templateFilename, [DIRECTORY_SEPARATOR => '/']);
137
			$templateFilename = preg_replace('/\\/+/', '/', $templateFilename);
138
			$parts = explode('/', $templateFilename);
139
			$correctedParts = [];
140
			foreach($parts as $part) {
141
				if($part === '.') {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
142
					// Skip
143
				} elseif($part === '..') {
144
					if(count($correctedParts)) {
145
						array_pop($correctedParts);
146
					} else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
147
						// Skip
148
					}
149
				} else {
150
					$correctedParts[] = $part;
151
				}
152
			}
153
			return join('/', $correctedParts);
154
		}
155
		return $templateFilename;
156
	}
157
}
158