caching and cache time configuration
[phancap.git] / src / phancap / Repository.php
1 <?php
2 namespace phancap;
3
4 class Repository
5 {
6     public function setConfig(Config $config)
7     {
8         $this->config = $config;
9     }
10
11     public function getImage(Options $options)
12     {
13         $name = $this->getFilename($options);
14         $img = new Image($name);
15         $img->setConfig($this->config);
16         if (!$this->isAvailable($img, $options)) {
17             $this->render($img, $options);
18         }
19         return $img;
20     }
21
22     public function getFilename(Options $options)
23     {
24         $optValues = $options->values;
25         unset($optValues['smaxage']);
26         unset($optValues['atimestamp']);
27         unset($optValues['asignature']);
28         unset($optValues['atoken']);
29
30         return parse_url($optValues['url'], PHP_URL_HOST)
31             . '-' . md5(\serialize($optValues))
32             . '.' . $optValues['sformat'];
33     }
34
35     /**
36      * Check if the image is available locally.
37      *
38      * @return boolean True if we have it and it's within the cache lifetime,
39      *                 false if the cache expired or the screenshot does not
40      *                 exist.
41      */
42     public function isAvailable(Image $img, Options $options)
43     {
44         $path = $img->getPath();
45         if (!file_exists($path)) {
46             return false;
47         }
48
49         if (filemtime($path) < time() - $options->values['smaxage']) {
50             return false;
51         }
52
53         return true;
54     }
55
56     protected function render(Image $img, Options $options)
57     {
58         $adapter = new Adapter_Cutycapt();
59         $adapter->render($img, $options);
60     }
61 }
62 ?>