1: <?php
2: /**
3: * This file is part of the Autarky package.
4: *
5: * (c) Andreas Lutro <anlutro@gmail.com>
6: *
7: * For the full copyright and license information, please view the LICENSE
8: * file that was distributed with this source code.
9: */
10:
11: namespace Autarky\Config\Loaders;
12:
13: use Symfony\Component\Yaml\Parser;
14:
15: /**
16: * Caching wrapper for the YAML/YML config file loader.
17: */
18: class CachingYamlFileLoader extends YamlFileLoader
19: {
20: /**
21: * The directory in which to look for cached files.
22: *
23: * @var string
24: */
25: protected $cacheDir;
26:
27: /**
28: * Whether or not to check if cache files are outdated.
29: *
30: * @var bool
31: */
32: protected $stat;
33:
34: /**
35: * Constructor.
36: *
37: * @param Parser $parser
38: * @param string $cacheDir
39: * @param bool $stat
40: */
41: public function __construct(Parser $parser, $cacheDir, $stat = true)
42: {
43: parent::__construct($parser);
44: $this->cacheDir = $cacheDir;
45: $this->stat = (bool) $stat;
46: }
47:
48: /**
49: * {@inheritdoc}
50: */
51: public function load($path)
52: {
53: $cachePath = $this->cacheDir.'/'.md5($path);
54:
55: if ($this->shouldLoadCache($path, $cachePath)) {
56: return require $cachePath;
57: }
58:
59: $data = parent::load($path);
60:
61: $this->filesys->write($cachePath, '<?php return '.var_export($data, true).";\n");
62:
63: return $data;
64: }
65:
66: protected function shouldLoadCache($path, $cachePath)
67: {
68: if (!file_exists($cachePath)) {
69: return false;
70: }
71:
72: if (!$this->stat) {
73: return true;
74: }
75:
76: // if the cache file is more recent than the real file,
77: // the cache file should be loaded
78: return filemtime($cachePath) > filemtime($path);
79: }
80: }
81: