19bc7c0e625f2ab22f2f57e1d2e8f68dd1728bce
[GitHub/WoltLab/WCF.git] /
1 <?php
2 /**
3 * PHP-DI
4 *
5 * @link http://php-di.org/
6 * @copyright Matthieu Napoli (http://mnapoli.fr/)
7 * @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file)
8 */
9
10 namespace DI\Definition\Source;
11
12 use DI\Definition\CacheableDefinition;
13 use DI\Definition\Definition;
14 use Doctrine\Common\Cache\Cache;
15
16 /**
17 * Caches another definition source.
18 *
19 * @author Matthieu Napoli <matthieu@mnapoli.fr>
20 */
21 class CachedDefinitionSource implements DefinitionSource
22 {
23 /**
24 * Prefix for cache key, to avoid conflicts with other systems using the same cache
25 * @var string
26 */
27 const CACHE_PREFIX = 'DI\\Definition\\';
28
29 /**
30 * @var DefinitionSource
31 */
32 private $source;
33
34 /**
35 * @var Cache
36 */
37 private $cache;
38
39 public function __construct(DefinitionSource $source, Cache $cache)
40 {
41 $this->source = $source;
42 $this->cache = $cache;
43 }
44
45 /**
46 * {@inheritdoc}
47 */
48 public function getDefinition($name)
49 {
50 // Look in cache
51 $definition = $this->fetchFromCache($name);
52
53 if ($definition === false) {
54 $definition = $this->source->getDefinition($name);
55
56 // Save to cache
57 if ($definition === null || ($definition instanceof CacheableDefinition)) {
58 $this->saveToCache($name, $definition);
59 }
60 }
61
62 return $definition;
63 }
64
65 /**
66 * @return Cache
67 */
68 public function getCache()
69 {
70 return $this->cache;
71 }
72
73 /**
74 * Fetches a definition from the cache
75 *
76 * @param string $name Entry name
77 * @return Definition|null|boolean The cached definition, null or false if the value is not already cached
78 */
79 private function fetchFromCache($name)
80 {
81 $cacheKey = self::CACHE_PREFIX . $name;
82
83 $data = $this->cache->fetch($cacheKey);
84
85 if ($data !== false) {
86 return $data;
87 }
88
89 return false;
90 }
91
92 /**
93 * Saves a definition to the cache
94 *
95 * @param string $name Entry name
96 * @param Definition|null $definition
97 */
98 private function saveToCache($name, Definition $definition = null)
99 {
100 $cacheKey = self::CACHE_PREFIX . $name;
101
102 $this->cache->save($cacheKey, $definition);
103 }
104 }