/
CacheLoader.php
97 lines (82 loc) · 2.71 KB
/
CacheLoader.php
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
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Templating\Loader;
use Symfony\Component\Templating\Storage\Storage;
use Symfony\Component\Templating\Storage\FileStorage;
use Symfony\Component\Templating\TemplateReferenceInterface;
/**
* CacheLoader is a loader that caches other loaders responses
* on the filesystem.
*
* This cache only caches on disk to allow PHP accelerators to cache the opcodes.
* All other mechanism would imply the use of `eval()`.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class CacheLoader extends Loader
{
protected $loader;
protected $dir;
/**
* Constructor.
*
* @param LoaderInterface $loader A Loader instance
* @param string $dir The directory where to store the cache files
*/
public function __construct(LoaderInterface $loader, $dir)
{
$this->loader = $loader;
$this->dir = $dir;
}
/**
* Loads a template.
*
* @param TemplateReferenceInterface $template A template
*
* @return Storage|Boolean false if the template cannot be loaded, a Storage instance otherwise
*/
public function load(TemplateReferenceInterface $template)
{
$key = hash('sha256', $template->getLogicalName());
$dir = $this->dir.DIRECTORY_SEPARATOR.substr($key, 0, 2);
$file = substr($key, 2).'.tpl';
$path = $dir.DIRECTORY_SEPARATOR.$file;
if (is_file($path)) {
if (null !== $this->debugger) {
$this->debugger->log(sprintf('Fetching template "%s" from cache', $template->get('name')));
}
return new FileStorage($path);
}
if (false === $storage = $this->loader->load($template)) {
return false;
}
$content = $storage->getContent();
if (!is_dir($dir)) {
mkdir($dir, 0777, true);
}
file_put_contents($path, $content);
if (null !== $this->debugger) {
$this->debugger->log(sprintf('Storing template "%s" in cache', $template->get('name')));
}
return new FileStorage($path);
}
/**
* Returns true if the template is still fresh.
*
* @param TemplateReferenceInterface $template A template
* @param integer $time The last modification time of the cached template (timestamp)
*
* @return Boolean
*/
public function isFresh(TemplateReferenceInterface $template, $time)
{
return $this->loader->isFresh($template, $time);
}
}