1 <?php
2
3 4 5 6 7 8 9 10
11
12 namespace ICanBoogie\CLDR;
13
14 15 16
17 interface Cache
18 {
19 20 21 22 23
24 public function exists($key);
25
26 27 28 29 30
31 public function retrieve($key);
32
33 34 35 36 37 38
39 public function store($key, $data);
40 }
41
42 43 44 45 46 47 48 49 50 51 52
53 class FileCache implements Cache
54 {
55 protected $root;
56
57 static private function path_to_key($path)
58 {
59 return str_replace('/', '--', $path);
60 }
61
62 public function __construct($root)
63 {
64 $this->root = rtrim($root, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
65 }
66
67 public function exists($path)
68 {
69 $key = self::path_to_key($path);
70 $filename = $this->root . $key;
71
72 return file_exists($filename);
73 }
74
75 public function retrieve($path)
76 {
77 $key = self::path_to_key($path);
78 $filename = $this->root . $key;
79
80 if (!file_exists($filename))
81 {
82 return;
83 }
84
85 return file_get_contents($filename);
86 }
87
88 public function store($path, $data)
89 {
90 $key = self::path_to_key($path);
91 $filename = $this->root . $key;
92
93 file_put_contents($filename, $data);
94 }
95 }
96
97 98 99 100 101 102 103 104 105 106 107 108 109 110
111 class RunTimeCache implements Cache
112 {
113 private $cache = array();
114 private $static_cache;
115
116 public function __construct(Cache $static_cache)
117 {
118 $this->static_cache = $static_cache;
119 }
120
121 public function exists($path)
122 {
123 if (array_key_exists($path, $this->cache))
124 {
125 return true;
126 }
127
128 return parent::exists($path);
129 }
130
131 public function retrieve($path)
132 {
133 if (array_key_exists($path, $this->cache))
134 {
135 return $this->cache[$path];
136 }
137
138 return $this->cache[$path] = $this->static_cache->retrieve($path);
139 }
140
141 public function store($path, $data)
142 {
143 $this->cache[$path] = $data;
144
145 $this->static_cache->store($path, $data);
146 }
147 }