1
|
|
|
<?php |
2
|
|
|
/* @description Transformation Style Sheets - Revolutionising PHP templating * |
3
|
|
|
* @author Tom Butler [email protected] * |
4
|
|
|
* @copyright 2017 Tom Butler <[email protected]> | https://r.je/ * |
5
|
|
|
* @license http://www.opensource.org/licenses/bsd-license.php BSD License * |
6
|
|
|
* @version 1.2 */ |
7
|
|
|
namespace Transphporm; |
8
|
|
|
//Separates out TSS file loading/caching from parsing |
9
|
|
|
class SheetCache { |
10
|
|
|
private $cacheKey; |
11
|
|
|
private $cacheName; |
12
|
|
|
private $cache; |
13
|
|
|
|
14
|
|
|
public function __construct(Cache $cache) { |
15
|
|
|
$this->cache = $cache; |
16
|
|
|
} |
17
|
|
|
|
18
|
|
View Code Duplication |
private function getRulesFromCache($file) { |
|
|
|
|
19
|
|
|
//Try to load the cached rules, if not set in the cache (or expired) parse the supplied sheet |
20
|
|
|
$rules = $this->cache->load($this->cacheName, filemtime($file)); |
21
|
|
|
|
22
|
|
|
$this->cacheKey = $this->cacheKey ?? $rules['cacheKey'] ?? null; |
23
|
|
|
|
24
|
|
|
if ($rules) { |
25
|
|
|
foreach ($rules['import'] as $file) { |
26
|
|
|
//Check that the import file hasn't been changed since the cache was written |
27
|
|
|
if (filemtime($file) > $rules['ctime']) return false; |
28
|
|
|
} |
29
|
|
|
} |
30
|
|
|
return $rules; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
View Code Duplication |
public function getCacheKey($tss, $data) { |
|
|
|
|
34
|
|
|
//Read the rules so that $this->cacheKey is set |
35
|
|
|
if (is_file($tss)) $this->getRulesFromCache($tss); |
36
|
|
|
if ($this->cacheKey) { |
37
|
|
|
$parser = new Parser\Value($data); |
38
|
|
|
$parsedKey = $parser->parseTokens($this->cacheKey)[0]; |
39
|
|
|
$this->cacheName = $parsedKey . $this->tss; |
|
|
|
|
40
|
|
|
return $parsedKey; |
41
|
|
|
} |
42
|
|
|
else return ''; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
|
46
|
|
|
//write the sheet to cache |
47
|
|
|
public function write($file, $rules, $imports = []) { |
48
|
|
|
if (is_file($file)) { |
49
|
|
|
$existing = $this->cache->load($file, filemtime($file)); |
50
|
|
|
if (isset($existing['import'])) $imports = $existing['import']; |
51
|
|
|
$this->cache->write($this->cacheName, ['rules' => $rules, 'import' => $imports, 'minFreq' => $this->getMinUpdateFreq($rules), 'ctime' => $this->time, 'cacheKey' => $this->cacheKey]); |
|
|
|
|
52
|
|
|
} |
53
|
|
|
return $rules; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
public function setKey($key) { |
57
|
|
|
$this->cacheKey = $key; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
} |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.