Completed
Push — master ( 6955e0...61fff4 )
by Michal
33:13 queued 31:42
created

TemplateRouter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 49
Duplicated Lines 100 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 0
dl 49
loc 49
rs 10
c 0
b 0
f 0

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
declare(strict_types=1);
3
4
use Nette\Application\Routers;
5
use \Nette\Bridges\ApplicationLatte\ILatteFactory;
6
7
8
/**
9
 * Micro-framework router for templates using {url} macro.
10
 */
11
class TemplateRouter extends Routers\RouteList
12
{
13
	/** @var ILatteFactory  */
14
	private $latteFactory;
15
16
	public function __construct($path, $cachePath, ILatteFactory $latteFactory)
17
	{
18
		parent::__construct();
19
		$this->latteFactory = $latteFactory;
20
21
		if (is_file($cacheFile = $cachePath . '/routes.php')) {
22
			$routes = require $cacheFile;
23
		} else {
24
			$routes = $this->scanRoutes($path);
25
			file_put_contents($cacheFile, '<?php return ' . var_export($routes, true) . ';');
26
		}
27
28
		foreach ($routes as $mask => $file) {
29
			$this[] = new Routers\Route($mask, function ($presenter) use ($file, $cachePath, $latteFactory) {
30
				return $presenter->createTemplate(null, [$this, 'createLatte'])->setFile($file);
31
			});
32
		}
33
	}
34
35
36
	public function scanRoutes($path)
37
	{
38
		$routes = [];
39
40
		$latte = $this->createLatte();
41
		$macroSet = new Latte\Macros\MacroSet($latte->getCompiler());
42
		$macroSet->addMacro('url', function ($node) use (&$routes, &$file) {
43
			$routes[$node->args] = (string) $file;
44
		}, null, null, $macroSet::ALLOWED_IN_HEAD);
45
46
		foreach (Nette\Utils\Finder::findFiles('*.latte')->from($path) as $file) {
47
			$latte->compile($file);
48
		}
49
50
		return $routes;
51
	}
52
53
	public function createLatte() {
54
		$latte = $this->latteFactory->create();
55
		$macroSet = new Latte\Macros\MacroSet($latte->getCompiler());
56
		$macroSet->addMacro('url', function () {}, null, null, $macroSet::ALLOWED_IN_HEAD); // ignore
57
		return $latte;
58
	}
59
}
60