TemplateManager   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 89
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 0
dl 0
loc 89
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getTemplate() 0 14 3
A monitor() 0 4 1
A isMonitored() 0 4 1
A createMap() 0 16 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SixtyEightPublishers\Application\Components;
6
7
use Nette\Utils\FileSystem;
8
use Nette\Utils\Finder;
9
use Nette\Utils\Strings;
10
11
class TemplateManager
12
{
13
	/** @var array  */
14
	private $map;
15
16
	/** @var string */
17
	private $templatesDir;
18
19
	/** @var array */
20
	private $monitoredComponents = [];
21
22
	/**
23
	 * @param array         $map
24
	 * @param string|NULL   $templatesDir
25
	 */
26
	public function __construct(array $map = [], string $templatesDir = NULL)
27
	{
28
		$this->map = $map;
29
		$this->templatesDir = (string) $templatesDir;
30
	}
31
32
	/**
33
	 * @param string $presenterName
34
	 * @param string $lookupPath
35
	 * @param string $templateFile
36
	 *
37
	 * @return NULL|string
38
	 */
39
	public function getTemplate(string $presenterName, string $lookupPath, string $templateFile)
40
	{
41
		if (!$this->isMonitored($presenterName, $lookupPath)) {
42
			return NULL;
43
		}
44
45
		$lookupPath = str_replace('-', '/', $lookupPath);
46
		$templateFile = explode('/', str_replace('\\', '/', $templateFile));
47
		$regex = '#^' . $presenterName . '/' . $lookupPath . '/' . $templateFile[count($templateFile) - 1] . '$#i';
48
49
		$matches = preg_grep($regex, $this->map);
50
51
		return count($matches) ? $this->templatesDir . '/' . $matches[array_keys($matches)[0]] : NULL;
52
	}
53
54
	/**
55
	 * @param string $presenterName
56
	 * @param string $lookupPath
57
	 *
58
	 * @return void
59
	 */
60
	public function monitor(string $presenterName, string $lookupPath)
61
	{
62
		$this->monitoredComponents[] = Strings::lower("{$presenterName}/{$lookupPath}");
63
	}
64
65
	/**
66
	 * @param string $presenterName
67
	 * @param string $lookupPath
68
	 *
69
	 * @return bool
70
	 */
71
	public function isMonitored(string $presenterName, string $lookupPath)
72
	{
73
		return in_array(Strings::lower("{$presenterName}/{$lookupPath}"), $this->monitoredComponents);
74
	}
75
76
77
	/**
78
	 * @internal
79
	 * @param string $dir
80
	 *
81
	 * @return array
82
	 */
83
	public static function createMap(string $dir)
84
	{
85
		FileSystem::createDir($dir);
86
		$map = [];
87
88
		/** @var \SplFileInfo $file */
89
		foreach (Finder::find('*.latte')->from($dir) as $file) {
90
			$path = Strings::trim(str_replace($dir, '', $file->getPathname()), "\\/");
91
92
			if (!Strings::contains($path, '@')) {
93
				$map[] = str_replace('\\', '/', $path);
94
			}
95
		}
96
97
		return $map;
98
	}
99
}
100