Completed
Pull Request — master (#2775)
by Jeroen
10:25
created

ResourceCacher::flushCache()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 8
cp 0
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 6
1
<?php
2
3
namespace Kunstmaan\TranslatorBundle\Service\Translator;
4
5
use Symfony\Component\Config\ConfigCache;
6
use Symfony\Component\Finder\Finder;
7
8
/**
9
 * ResourceCacher is used to cache all the resource into a file
10
 */
11
class ResourceCacher
12
{
13
    /**
14
     * @var bool
15
     */
16
    private $debug;
17
18
    /**
19
     * Where to store cache files
20
     *
21
     * @var string
22
     */
23
    private $cacheDir;
24
25
    /**
26
     * Logger
27
     *
28
     * @var \Symfony\Component\HttpKernel\Log\LoggerInterface
29
     */
30
    private $logger;
31
32
    /**
33
     * Retrieve resources from cache file (if any)
34
     *
35
     * @return resources false if empty
36
     */
37
    public function getCachedResources()
38
    {
39
        $resources = false;
40
41
        $cache = new ConfigCache($this->getCacheFileLocation(), $this->debug);
42
43
        if ($cache->isFresh()) {
44
            $this->logger->debug('Loading translation resources from cache file.');
45
46
            return include $this->getCacheFileLocation();
47
        }
48
49
        return $resources;
50
    }
51
52
    /**
53
     * Cache an array of resources into the given cache
54
     *
55
     * @param array $resources
56
     */
57
    public function cacheResources(array $resources)
58
    {
59
        $cache = new ConfigCache($this->getCacheFileLocation(), $this->debug);
60
        $content = sprintf('<?php return %s;', var_export($resources, true));
61
        $cache->write($content);
62
        $this->logger->debug('Writing translation resources to cache file.');
63
    }
64
65
    /**
66
     * Get cache file location
67
     *
68
     * @return string
69
     */
70
    public function getCacheFileLocation()
71
    {
72
        return sprintf('%s/resources.cached.php', $this->cacheDir);
73
    }
74
75
    /**
76
     * Remove all cached files (translations/resources)
77
     */
78
    public function flushCache()
79
    {
80
        $finder = new Finder();
81
82
        foreach ($finder->files()->in($this->cacheDir)->name('*.php') as $file) {
83
            unlink($file->getRealpath());
84
        }
85
86
        return true;
87
    }
88
89
    public function setDebug($debug)
90
    {
91
        $this->debug = $debug;
92
    }
93
94
    public function setCacheDir($cacheDir)
95
    {
96
        $this->cacheDir = $cacheDir;
97
    }
98
99
    public function setLogger($logger)
100
    {
101
        $this->logger = $logger;
102
    }
103
}
104