Completed
Push — master ( 7c92dc...c428b0 )
by Jean-Christophe
01:30
created

RestCacheTrait::getRestResource()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
namespace micro\cache\traits;
3
4
use micro\cache\ClassUtils;
5
use micro\cache\parser\RestControllerParser;
6
use micro\utils\JArray;
7
use micro\exceptions\RestException;
8
use micro\utils\FsUtils;
9
10
/**
11
 * @author jc
12
 * @staticvar array $cache
13
 *
14
 */
15
trait RestCacheTrait{
16
17
	private static function initRestCache(&$config,$silent=false) {
18
		$restCache=[];
19
		$files=self::getControllersFiles($config);
20
		foreach ( $files as $file ) {
21
			if (is_file($file)) {
22
				$controller=ClassUtils::getClassFullNameFromFile($file);
23
				$parser=new RestControllerParser();
24
				$parser->parse($controller,$config);
25
				if($parser->isRest())
26
					$restCache=\array_merge($restCache,$parser->asArray());
27
			}
28
		}
29
		self::$cache->store("controllers/rest", "return " . JArray::asPhpArray($restCache, "array") . ";");
30
		if(!$silent){
31
			echo "Rest cache reset\n";
32
		}
33
	}
34
35
	public static function getRestRoutes() {
36
		$result=[];
37
		$restCache=self::getRestCache();
38
		foreach ($restCache as $controllerClass=>$restAttributes){
39
			if(isset($restCache[$controllerClass])){
40
				$result[$controllerClass]=["restAttributes"=>$restAttributes,"routes"=>self::getControllerRoutes($controllerClass,true)];
41
			}
42
		}
43
		return $result;
44
	}
45
46
	public static function getRestCache() {
47
		if (self::$cache->exists("controllers/rest"))
48
			return self::$cache->fetch("controllers/rest");
49
			throw new RestException("Rest cache does not exist : the file `".FsUtils::cleanPathname(ROOT.DS.self::getCacheDirectory()."controllers/")."rest.cache.php` is missing.\nTry to Re-init Rest cache.");
50
	}
51
52
	public static function getRestResource($controllerClass){
53
		$cacheControllerClass=self::getRestCacheController($controllerClass);
54
		if(isset($cacheControllerClass))
55
			return $cacheControllerClass["resource"];
56
		return null;
57
	}
58
59
	public static function getRestCacheController($controllerClass){
60
		$cache=self::getRestCache();
61
		if(isset($cache[$controllerClass])){
62
			return $cache[$controllerClass];
63
		}
64
		return null;
65
	}
66
}
67