Completed
Push — master ( 56c8c7...7e918b )
by Matthieu
02:46
created

CachedDefinitionSource::getCacheKey()   A

Complexity

Conditions 1
Paths 1

Duplication

Lines 0
Ratio 0 %

Size

Total Lines 4
Code Lines 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace DI\Definition\Source;
4
5
use DI\Definition\CacheableDefinition;
6
use DI\Definition\Definition;
7
use Psr\SimpleCache\CacheInterface;
8
9
/**
10
 * Caches another definition source.
11
 *
12
 * @author Matthieu Napoli <[email protected]>
13
 */
14
class CachedDefinitionSource implements DefinitionSource
15
{
16
    /**
17
     * Prefix for cache key, to avoid conflicts with other systems using the same cache.
18
     * @var string
19
     */
20
    const CACHE_PREFIX = 'DI.Definition.';
21
22
    /**
23
     * @var DefinitionSource
24
     */
25
    private $source;
26
27
    /**
28
     * @var CacheInterface
29
     */
30
    private $cache;
31
32
    public function __construct(DefinitionSource $source, CacheInterface $cache)
33
    {
34
        $this->source = $source;
35
        $this->cache = $cache;
36
    }
37
38
    public function getDefinition(string $name)
39
    {
40
        // Look in cache
41
        $definition = $this->fetchFromCache($name);
42
43
        if ($definition === false) {
44
            $definition = $this->source->getDefinition($name);
45
46
            // Save to cache
47
            if ($definition === null || ($definition instanceof CacheableDefinition)) {
48
                $this->saveToCache($name, $definition);
49
            }
50
        }
51
52
        return $definition;
53
    }
54
55
    public function getCache() : CacheInterface
56
    {
57
        return $this->cache;
58
    }
59
60
    /**
61
     * Fetches a definition from the cache.
62
     *
63
     * @param string $name Entry name
64
     * @return Definition|null|bool The cached definition, null or false if the value is not already cached
65
     */
66
    private function fetchFromCache(string $name)
67
    {
68
        $data = $this->cache->get($this->getCacheKey($name), false);
69
70
        if ($data !== false) {
71
            return $data;
72
        }
73
74
        return false;
75
    }
76
77
    /**
78
     * Saves a definition to the cache.
79
     *
80
     * @param string $name Entry name
81
     */
82
    private function saveToCache(string $name, Definition $definition = null)
83
    {
84
        $this->cache->set($this->getCacheKey($name), $definition);
85
    }
86
87
    /**
88
     * Get normalized cache key.
89
     *
90
     * @param string $name
91
     *
92
     * @return string
93
     */
94
    private function getCacheKey(string $name) : string
95
    {
96
        return self::CACHE_PREFIX . str_replace(['{', '}', '(', ')', '/', '\\', '@', ':'], '.', $name);
97
    }
98
}
99