diff options
| author | Christian Weiske <cweiske@cweiske.de> | 2015-07-07 16:10:56 +0200 |
|---|---|---|
| committer | Christian Weiske <cweiske@cweiske.de> | 2015-07-07 16:10:56 +0200 |
| commit | 2cd81a74dcf24acf85c86639ad60a140037d4451 (patch) | |
| tree | 4bc925ee86b2b2060f774e6270134cde06571db6 /src/phorkie/Renderer/Cache.php | |
| parent | 246ac1d5966639f2036795d859cb2b195c762236 (diff) | |
| download | phorkie-2cd81a74dcf24acf85c86639ad60a140037d4451.tar.gz phorkie-2cd81a74dcf24acf85c86639ad60a140037d4451.zip | |
simple cache for rendered files
Diffstat (limited to 'src/phorkie/Renderer/Cache.php')
| -rw-r--r-- | src/phorkie/Renderer/Cache.php | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/src/phorkie/Renderer/Cache.php b/src/phorkie/Renderer/Cache.php new file mode 100644 index 0000000..4137b05 --- /dev/null +++ b/src/phorkie/Renderer/Cache.php @@ -0,0 +1,84 @@ +<?php +namespace phorkie; + +class Renderer_Cache +{ + /** + * Converts the code to HTML by fetching it from cache, + * or by letting the other renderes generate it and then + * storing it in the cache. + * + * @param File $file File to render + * @param Tool_Result $res Tool result to integrate + * + * @return string HTML + */ + public function toHtml(File $file, Tool_Result $res = null) + { + $html = null; + $cacheFile = $this->getCacheFile($file); + if ($res === null && $cacheFile !== null) { + $html = $this->loadHtmlFromCache($cacheFile); + } + if ($html === null) { + $html = $this->renderFile($file, $res); + if ($res === null && $cacheFile !== null) { + $this->storeHtmlIntoCache($cacheFile, $html); + } + } + return $html; + } + + protected function renderFile(File $file, Tool_Result $res = null) + { + $ext = $file->getExt(); + $class = '\\phorkie\\Renderer_Unknown'; + + if (isset($GLOBALS['phorkie']['languages'][$ext]['renderer'])) { + $class = $GLOBALS['phorkie']['languages'][$ext]['renderer']; + } else if ($file->isText()) { + $class = '\\phorkie\\Renderer_Geshi'; + } else if (isset($GLOBALS['phorkie']['languages'][$ext]['mime'])) { + $type = $GLOBALS['phorkie']['languages'][$ext]['mime']; + if (substr($type, 0, 6) == 'image/') { + $class = '\\phorkie\\Renderer_Image'; + } + } + + $rend = new $class(); + return $rend->toHtml($file, $res); + } + + /** + * @return null|string NULL when there is no cache, string with HTML + * otherwise + */ + protected function loadHtmlFromCache($cacheFile) + { + if (!file_exists($cacheFile)) { + return null; + } + return file_get_contents($cacheFile); + } + + protected function storeHtmlIntoCache($cacheFile, $html) + { + file_put_contents($cacheFile, $html); + } + + protected function getCacheFile(File $file) + { + if (!$GLOBALS['phorkie']['cfg']['cachedir'] + || !is_dir($GLOBALS['phorkie']['cfg']['cachedir']) + ) { + return null; + } + + return $GLOBALS['phorkie']['cfg']['cachedir'] + . '/' . $file->repo->id + . '-' . $file->repo->hash + . '-' . str_replace('/', '-', $file->getFilename()) + . '.html'; + } +} +?> |
