Completed
Push — master ( 25576f...77f108 )
by Jean-Christophe
02:06
created

CacheManager   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 178
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 46
c 1
b 0
f 0
lcom 1
cbo 5
dl 0
loc 178
rs 8.3999

19 Methods

Rating   Name   Duplication   Size   Complexity  
A start() 0 7 1
A startProd() 0 5 1
A getControllerCache() 0 5 2
A initialGetCacheDirectory() 0 8 2
A getCacheDirectory() 0 3 1
A createOrmModelCache() 0 9 2
A addControllerCache() 0 9 2
A checkCache() 0 15 1
A safeMkdir() 0 4 2
A deleteAllFilesFromFolder() 0 7 3
B clearCache() 0 12 8
B initCache() 0 8 5
B initModelsCache() 0 15 5
A getClassNameFromFile() 0 4 1
B initControllersCache() 0 18 6
A register() 0 14 1
A addAdminRoutes() 0 3 1
A getRoutes() 0 4 1
A addRoute() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like CacheManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use CacheManager, and based on these observations, apply Extract Interface, too.

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
	private static $cacheDirectory;
14
15
	public static function start(&$config){
16
		self::$cacheDirectory=self::initialGetCacheDirectory($config);
17
		$cacheDirectory=ROOT.DS.self::$cacheDirectory;
18
		Annotations::$config['cache'] = new AnnotationCache($cacheDirectory.'/annotations');
19
		self::register(Annotations::getManager());
20
		self::$cache=new ArrayCache($cacheDirectory,".cache");
21
	}
22
23
	public static function startProd(&$config){
24
		self::$cacheDirectory=self::initialGetCacheDirectory($config);
25
		$cacheDirectory=ROOT.DS.self::$cacheDirectory;
26
		self::$cache=new ArrayCache($cacheDirectory,".cache");
27
	}
28
29
	public static function getControllerCache(){
30
		if(self::$cache->exists("controllers/routes"))
31
			return self::$cache->fetch("controllers/routes");
32
		return [];
33
	}
34
35
	private static function initialGetCacheDirectory(&$config){
36
		$cacheDirectory=@$config["cacheDirectory"];
37
		if(!isset($cacheDirectory)){
38
			$config["cacheDirectory"]="cache/";
39
			$cacheDirectory=$config["cacheDirectory"];
40
		}
41
		return $cacheDirectory;
42
	}
43
44
	public static function getCacheDirectory(){
45
		return self::$cacheDirectory;
46
	}
47
48
	public static function createOrmModelCache($className){
49
		$key=\str_replace("\\", DIRECTORY_SEPARATOR, $className);
50
		if(!self::$cache->exists($key)){
51
			$p=new ModelParser();
52
			$p->parse($className);
53
			self::$cache->store($key, $p->__toString());
54
		}
55
		return self::$cache->fetch($key);
56
	}
57
58
	private static function addControllerCache($classname){
59
			$parser=new ControllerParser();
60
			try {
61
				$parser->parse($classname);
62
				self::$routes=\array_merge($parser->asArray(),self::$routes);
63
			} catch (\Exception $e) {
64
				//Nothing to do
65
			}
66
	}
67
68
	public static function checkCache(&$config){
69
		$cacheDirectory=self::getCacheDirectory($config);
0 ignored issues
show
Unused Code introduced by
The call to CacheManager::getCacheDirectory() has too many arguments starting with $config.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
70
		$modelsDir=str_replace("\\", DS, $config["mvcNS"]["models"]);
71
		$controllersDir=str_replace("\\", DS, $config["mvcNS"]["controllers"]);
72
		echo "cache directory is ".ROOT.DS.$cacheDirectory."\n";
73
		$annotationCacheDir=ROOT.DS.$cacheDirectory.DS."annotations";
74
		$modelsCacheDir=ROOT.DS.$cacheDirectory.DS.$modelsDir;
75
		$queriesCacheDir=ROOT.DS.$cacheDirectory.DS."queries";
76
		$controllersCacheDir=ROOT.DS.$cacheDirectory.DS.$controllersDir;
77
		self::safeMkdir($annotationCacheDir);
78
		self::safeMkdir($modelsCacheDir);
79
		self::safeMkdir($controllersCacheDir);
80
		self::safeMkdir($queriesCacheDir);
81
		return ["annotations"=>$annotationCacheDir,"models"=>$modelsCacheDir,"controllers"=>$controllersCacheDir,"queries"=>$queriesCacheDir];
82
	}
83
84
	private static function safeMkdir($dir){
85
		if(!is_dir($dir))
86
			return mkdir($dir,0777,true);
87
	}
88
89
	private static function deleteAllFilesFromFolder($folder){
90
		$files = glob($folder.'/*');
91
		foreach($files as $file){
92
			if(is_file($file))
93
				unlink($file);
94
		}
95
	}
96
	public static function clearCache(&$config,$type="all"){
97
		$cacheDirectories=self::checkCache($config);
98
		if($type==="all"){
99
			self::deleteAllFilesFromFolder($cacheDirectories["annotations"]);
100
		}
101
		if($type==="all" || $type==="controllers")
102
			self::deleteAllFilesFromFolder($cacheDirectories["controllers"]);
103
		if($type==="all" || $type==="models")
104
			self::deleteAllFilesFromFolder($cacheDirectories["models"]);
105
		if($type==="all" || $type==="queries")
106
			self::deleteAllFilesFromFolder($cacheDirectories["queries"]);
107
	}
108
109
	public static function initCache(&$config,$type="all"){
110
		self::checkCache($config);
111
		self::start($config);
112
		if($type==="all" || $type==="models")
113
			self::initModelsCache($config);
114
		if($type==="all" || $type==="controllers")
115
			self::initControllersCache($config);
116
	}
117
118
	private static function initModelsCache(&$config){
119
		$modelsNS=$config["mvcNS"]["models"];
120
		$modelsDir=ROOT.DS.str_replace("\\", DS, $modelsNS);
121
		echo "Models directory is ".ROOT.$modelsNS."\n";
122
		$files = glob($modelsDir.DS.'*');
123
		$namespace="";
124
		if(isset($modelsNS) && $modelsNS!=="")
125
			$namespace=$modelsNS."\\";
126
		foreach($files as $file){
127
			if(is_file($file)){
128
				$model=self::getClassNameFromFile($file,$namespace);
129
				new $model();
130
			}
131
		}
132
	}
133
134
	private static function getClassNameFromFile($file,$namespace=""){
135
		$fileName=pathinfo($file, PATHINFO_FILENAME);
136
		return $namespace.ucfirst($fileName);
137
	}
138
139
	private static function initControllersCache(&$config){
140
		$controllersNS=$config["mvcNS"]["controllers"];
141
		$controllersDir=ROOT.DS.str_replace("\\", DS, $controllersNS);
142
		echo "Controllers directory is ".ROOT.$controllersNS."\n";
143
		$files = glob($controllersDir.DS.'*');
144
		$namespace="";
145
		if(isset($controllersNS) && $controllersNS!=="")
146
			$namespace=$controllersNS."\\";
147
		foreach($files as $file){
148
			if(is_file($file)){
149
				$controller=self::getClassNameFromFile($file,$namespace);
150
				self::addControllerCache($controller);
151
			}
152
		}
153
		if($config["debug"])
154
			self::addAdminRoutes();
155
		self::$cache->store("controllers/routes", "return ".JArray::asPhpArray(self::$routes,"array").";");
156
	}
157
158
	private static function register(AnnotationManager $annotationManager){
159
		$annotationManager->registry=array_merge($annotationManager->registry,[
160
				'id' => 'micro\annotations\IdAnnotation',
161
				'manyToOne' => 'micro\annotations\ManyToOneAnnotation',
162
				'oneToMany' => 'micro\annotations\OneToManyAnnotation',
163
				'manyToMany' => 'micro\annotations\ManyToManyAnnotation',
164
				'joinColumn' => 'micro\annotations\JoinColumnAnnotation',
165
				'table' => 'micro\annotations\TableAnnotation',
166
				'transient' => 'micro\annotations\TransientAnnotation',
167
				'column' => 'micro\annotations\ColumnAnnotation',
168
				'joinTable' => 'micro\annotations\JoinTableAnnotation',
169
				'route' => 'micro\annotations\router\RouteAnnotation'
170
		]);
171
	}
172
173
	public static function addAdminRoutes(){
174
		self::addControllerCache("micro\controllers\Admin");
175
	}
176
177
	public static function getRoutes(){
178
		$result=self::getControllerCache();
179
		return $result;
180
	}
181
182
	public static function addRoute($path,$controller,$action="index",$methods=null,$name=""){
183
		$controllerCache=self::getControllerCache();
184
		Router::addRouteToRoutes($controllerCache, $path, $controller,$action,$methods,$name);
185
		self::$cache->store("controllers/routes","return ".JArray::asPhpArray($controllerCache,"array").";");
186
	}
187
}
188