Completed
Push — master ( 1fdf8c...1603d3 )
by Jean-Christophe
02:05
created

CacheManager::addRoute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 4
nc 1
nop 5
1
<?php
2
namespace micro\cache;
3
use mindplay\annotations\Annotations;
4
use mindplay\annotations\AnnotationCache;
5
use mindplay\annotations\AnnotationManager;
6
use micro\orm\parser\ModelParser;
7
use micro\utils\JArray;
8
use micro\controllers\Router;
9
10
class CacheManager {
11
	public static $cache;
12
	private static $routes=[];
13
14
	public static function start(&$config){
15
		$cacheDirectory=ROOT.DS.self::getCacheDirectory($config);
16
		Annotations::$config['cache'] = new AnnotationCache($cacheDirectory.'/annotations');
17
		self::register(Annotations::getManager());
18
		self::$cache=new AnnotationCache($cacheDirectory);
19
	}
20
21
	public static function startProd(&$config){
22
		$cacheDirectory=ROOT.DS.self::getCacheDirectory($config);
23
		self::$cache=new AnnotationCache($cacheDirectory);
24
	}
25
26
	public static function getControllerCache(){
27
		return self::$cache->fetch("controllers/routes");
28
	}
29
30
	public static function getCacheDirectory(&$config){
31
		$cacheDirectory=@$config["cacheDirectory"];
32
		if(!isset($cacheDirectory)){
33
			$config["cacheDirectory"]="cache/";
34
			$cacheDirectory=$config["cacheDirectory"];
35
		}
36
		return $cacheDirectory;
37
	}
38
39
	public static function createOrmModelCache($className){
40
		$key=\str_replace("\\", DIRECTORY_SEPARATOR, $className);
41
		if(!self::$cache->exists($key)){
42
			$p=new ModelParser();
43
			$p->parse($className);
44
			self::$cache->store($key, $p->__toString());
45
		}
46
		return self::$cache->fetch($key);
47
	}
48
49
	private static function addControllerCache($classname){
50
			$parser=new ControllerParser();
51
			try {
52
				$parser->parse($classname);
53
				self::$routes=\array_merge($parser->asArray(),self::$routes);
54
			} catch (\Exception $e) {
55
				//Nothing to do
56
			}
57
58
	}
59
60
	private static function checkCache(&$config){
61
		$cacheDirectory=self::getCacheDirectory($config);
62
		$modelsDir=str_replace("\\", DS, $config["mvcNS"]["models"]);
63
		$controllersDir=str_replace("\\", DS, $config["mvcNS"]["controllers"]);
64
		echo "cache directory is ".ROOT.DS.$cacheDirectory."\n";
65
		$annotationCacheDir=ROOT.DS.$cacheDirectory.DS."annotations";
66
		$modelsCacheDir=ROOT.DS.$cacheDirectory.DS.$modelsDir;
67
		$controllersCacheDir=ROOT.DS.$cacheDirectory.DS.$controllersDir;
68
		self::safeMkdir($annotationCacheDir);
69
		self::safeMkdir($modelsCacheDir);
70
		self::safeMkdir($controllersCacheDir);
71
		return ["annotations"=>$annotationCacheDir,"models"=>$modelsCacheDir,"controllers"=>$controllersCacheDir];
72
	}
73
74
	private static function safeMkdir($dir){
75
		if(!is_dir($dir))
76
			return mkdir($dir,0777,true);
77
	}
78
79
	private static function deleteAllFilesFromFolder($folder){
80
		$files = glob($folder.'/*');
81
		foreach($files as $file){
82
			if(is_file($file))
83
				unlink($file);
84
		}
85
	}
86
	public static function clearCache(&$config,$type="all"){
87
		$cacheDirectories=self::checkCache($config);
88
		if($type==="all"){
89
			self::deleteAllFilesFromFolder($cacheDirectories["annotations"]);
90
		}
91
		if($type==="all" || $type==="controllers")
92
			self::deleteAllFilesFromFolder($cacheDirectories["controllers"]);
93
		if($type==="all" || $type==="models")
94
			self::deleteAllFilesFromFolder($cacheDirectories["models"]);
95
	}
96
97
	public static function initCache(&$config,$type="all"){
98
		self::checkCache($config);
99
		self::start($config);
100
		if($type==="all" || $type==="models")
101
			self::initModelsCache($config);
102
		if($type==="all" || $type==="controllers")
103
			self::initControllersCache($config);
104
	}
105
106
	private static function initModelsCache(&$config){
107
		$modelsNS=$config["mvcNS"]["models"];
108
		$modelsDir=ROOT.DS.str_replace("\\", DS, $modelsNS);
109
		echo "Models directory is ".ROOT.$modelsNS."\n";
110
		$files = glob($modelsDir.DS.'*');
111
		$namespace="";
112
		if(isset($modelsNS) && $modelsNS!=="")
113
			$namespace=$modelsNS."\\";
114
		foreach($files as $file){
115
			if(is_file($file)){
116
				$model=self::getClassNameFromFile($file,$namespace);
117
				new $model();
118
			}
119
		}
120
	}
121
122
	private static function getClassNameFromFile($file,$namespace=""){
123
		$fileName=pathinfo($file, PATHINFO_FILENAME);
124
		return $namespace.ucfirst($fileName);
125
	}
126
127
	private static function initControllersCache(&$config){
128
		$controllersNS=$config["mvcNS"]["controllers"];
129
		$controllersDir=ROOT.DS.str_replace("\\", DS, $controllersNS);
130
		echo "Controllers directory is ".ROOT.$controllersNS."\n";
131
		$files = glob($controllersDir.DS.'*');
132
		$namespace="";
133
		if(isset($controllersNS) && $controllersNS!=="")
134
			$namespace=$controllersNS."\\";
135
		foreach($files as $file){
136
			if(is_file($file)){
137
				$controller=self::getClassNameFromFile($file,$namespace);
138
				self::addControllerCache($controller);
139
			}
140
		}
141
		if($config["debug"])
142
			self::addAdminRoutes();
143
		self::$cache->store("controllers/routes", "return ".JArray::asPhpArray(self::$routes,"array").";");
144
	}
145
146
	private static function register(AnnotationManager $annotationManager){
147
		$annotationManager->registry=array_merge($annotationManager->registry,[
148
				'id' => 'micro\annotations\IdAnnotation',
149
				'manyToOne' => 'micro\annotations\ManyToOneAnnotation',
150
				'oneToMany' => 'micro\annotations\OneToManyAnnotation',
151
				'manyToMany' => 'micro\annotations\ManyToManyAnnotation',
152
				'joinColumn' => 'micro\annotations\JoinColumnAnnotation',
153
				'table' => 'micro\annotations\TableAnnotation',
154
				'transient' => 'micro\annotations\TransientAnnotation',
155
				'column' => 'micro\annotations\ColumnAnnotation',
156
				'joinTable' => 'micro\annotations\JoinTableAnnotation',
157
				'route' => 'micro\annotations\router\RouteAnnotation'
158
		]);
159
	}
160
161
	public static function addAdminRoutes(){
162
		self::addControllerCache("micro\controllers\Admin");
163
	}
164
165
	public static function getRoutes(){
166
		$result=self::getControllerCache();
167
		return $result;
168
	}
169
170
	public static function addRoute($path,$controller,$action="index",$methods=null,$name=""){
171
		$controllerCache=self::$cache->fetch("controllers/routes");
172
		Router::addRouteToRoutes($controllerCache, $path, $controller,$action,$methods,$name);
173
		self::$cache->store("controllers/routes","return ".JArray::asPhpArray($controllerCache,"array").";");
174
	}
175
}
176