1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Nip\Inflector\Traits; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Trait HasCacheTrait |
7
|
|
|
* @package Nip\Inflector |
8
|
|
|
*/ |
9
|
|
|
trait HasCacheTrait |
10
|
|
|
{ |
11
|
|
|
protected $cacheFile = null; |
12
|
|
|
|
13
|
|
|
protected $toCache = false; |
14
|
|
|
/** |
15
|
|
|
* @param string $directory |
16
|
|
|
*/ |
17
|
|
|
public function setCachePath($directory) |
18
|
|
|
{ |
19
|
|
|
$file = $directory . DIRECTORY_SEPARATOR . 'inflector.php'; |
20
|
|
|
$this->setCacheFile($file); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param null|string $cacheFile |
25
|
|
|
*/ |
26
|
|
|
public function setCacheFile($cacheFile) |
27
|
|
|
{ |
28
|
|
|
$this->cacheFile = $cacheFile; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function readCache() |
32
|
|
|
{ |
33
|
|
|
if ($this->isCached()) { |
34
|
|
|
/** @noinspection PhpIncludeInspection */ |
35
|
|
|
include($this->cacheFile); |
36
|
|
|
|
37
|
|
|
/** @noinspection PhpUndefinedVariableInspection */ |
38
|
|
|
if ($inflector) { |
|
|
|
|
39
|
|
|
foreach ($inflector as $type => $words) { |
40
|
|
|
if ($words) { |
41
|
|
|
foreach ($words as $word => $inflection) { |
42
|
|
|
$this->dictionary[$type][$word] = $inflection; |
|
|
|
|
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @return bool |
52
|
|
|
*/ |
53
|
|
|
public function isCached() |
54
|
|
|
{ |
55
|
|
|
if ($this->hasCacheFile()) { |
56
|
|
|
if (filemtime($this->cacheFile) + $this->getCacheTTL() > time()) { |
57
|
|
|
return true; |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
return false; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @return bool |
66
|
|
|
*/ |
67
|
|
|
public function hasCacheFile() |
68
|
|
|
{ |
69
|
|
|
return ($this->cacheFile && file_exists($this->cacheFile)); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @return int |
74
|
|
|
*/ |
75
|
|
|
public function getCacheTTL() |
76
|
|
|
{ |
77
|
|
|
if (app()->has('config')) { |
78
|
|
|
$config = app()->get('config'); |
79
|
|
|
if ($config->has('MISC.inflector_cache')) { |
80
|
|
|
return $config->get('MISC.inflector_cache'); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
return 86400; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
public function __destruct() |
88
|
|
|
{ |
89
|
|
|
if ($this->toCache) { |
90
|
|
|
$this->writeCache(); |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
public function writeCache() |
95
|
|
|
{ |
96
|
|
|
if ($this->dictionary && $this->cacheFile) { |
97
|
|
|
$file = new \Nip_File_Handler(["path" => $this->cacheFile]); |
|
|
|
|
98
|
|
|
$data = '<?php $inflector = ' . var_export($this->dictionary, true) . ";"; |
99
|
|
|
$file->rewrite($data); |
100
|
|
|
} |
101
|
|
|
} |
102
|
|
|
} |
103
|
|
|
|