aboutsummaryrefslogtreecommitdiff
path: root/src/phorkie/Renderer/Cache.php
blob: 4137b05b181b42240a13a21c53a4c801a810d0ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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';
    }
}
?>