Update jQuery from 1.12.4 to 3.7.1
[phorkie.git] / src / phorkie / Renderer / Cache.php
1 <?php
2 namespace phorkie;
3
4 class Renderer_Cache
5 {
6     /**
7      * Converts the code to HTML by fetching it from cache,
8      * or by letting the other renderes generate it and then
9      * storing it in the cache.
10      *
11      * @param File        $file File to render
12      * @param Tool_Result $res  Tool result to integrate
13      *
14      * @return string HTML
15      */
16     public function toHtml(File $file, Tool_Result $res = null)
17     {
18         $html = null;
19         $cacheFile = $this->getCacheFile($file);
20         if ($res === null && $cacheFile !== null) {
21             $html = $this->loadHtmlFromCache($cacheFile);
22         }
23         if ($html === null) {
24             $html = $this->renderFile($file, $res);
25             if ($res === null && $cacheFile !== null) {
26                 $this->storeHtmlIntoCache($cacheFile, $html);
27             }
28         }
29         return $html;
30     }
31
32     protected function renderFile(File $file, Tool_Result $res = null)
33     {
34         $ext   = $file->getExt();
35         $class = '\\phorkie\\Renderer_Unknown';
36
37         if (isset($GLOBALS['phorkie']['languages'][$ext]['renderer'])) {
38             $class = $GLOBALS['phorkie']['languages'][$ext]['renderer'];
39         } else if ($file->isText()) {
40             $class = '\\phorkie\\Renderer_Geshi';
41         } else if (isset($GLOBALS['phorkie']['languages'][$ext]['mime'])) {
42             $type = $GLOBALS['phorkie']['languages'][$ext]['mime'];
43             if (substr($type, 0, 6) == 'image/') {
44                 $class = '\\phorkie\\Renderer_Image';
45             }
46         }
47
48         $rend = new $class();
49         return $rend->toHtml($file, $res);
50     }
51
52     /**
53      * @return null|string NULL when there is no cache, string with HTML
54      *                     otherwise
55      */
56     protected function loadHtmlFromCache($cacheFile)
57     {
58         if (!file_exists($cacheFile)) {
59             return null;
60         }
61         return file_get_contents($cacheFile);
62     }
63
64     protected function storeHtmlIntoCache($cacheFile, $html)
65     {
66         file_put_contents($cacheFile, $html);
67     }
68
69     protected function getCacheFile(File $file)
70     {
71         if (!$GLOBALS['phorkie']['cfg']['cachedir']
72             || !is_dir($GLOBALS['phorkie']['cfg']['cachedir'])
73         ) {
74             return null;
75         }
76
77         return $GLOBALS['phorkie']['cfg']['cachedir']
78             . '/' . $file->repo->id
79             . '-' . $file->repo->hash
80             . '-' . str_replace('/', '-', $file->getFilename())
81             . '.html';
82     }
83 }
84 ?>