Completed
Push — master ( aae586...fa230b )
by Tobias
12:29
created

CacheClearer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 3
crap 1
1
<?php
2
3
/*
4
 * This file is part of the PHP Translation package.
5
 *
6
 * (c) PHP Translation team <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Translation\Bundle\Service;
13
14
use Symfony\Component\Filesystem\Filesystem;
15
use Symfony\Component\Finder\Finder;
16
use Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface;
17
use Symfony\Component\Translation\TranslatorInterface;
18
19
/**
20
 * A service able to read and clear the Symfony Translation cache.
21
 *
22
 * @author Damien A. <[email protected]>
23
 */
24
final class CacheClearer
25
{
26
    /**
27
     * @var string
28
     */
29
    private $kernelCacheDir;
30
31
    /**
32
     * @var TranslatorInterface
33
     */
34
    private $translator;
35
36
    /**
37
     * @var Filesystem
38
     */
39
    private $filesystem;
40
41 1
    public function __construct($kernelCacheDir, TranslatorInterface $translator, Filesystem $filesystem)
42
    {
43 1
        $this->kernelCacheDir = $kernelCacheDir;
44 1
        $this->translator = $translator;
45 1
        $this->filesystem = $filesystem;
46 1
    }
47
48
    /**
49
     * Remove the Symfony translation cache and warm it up again.
50
     *
51
     * @param string|null $locale Optional filter to clear only one locale.
52
     */
53 1
    public function clearAndWarmUp($locale = null)
54
    {
55 1
        $translationDir = sprintf('%s/translations', $this->kernelCacheDir);
56
57 1
        $finder = new Finder();
58
59
        // Make sure the directory exists
60 1
        $this->filesystem->mkdir($translationDir);
61
62
        // Remove the translations for this locale
63 1
        $files = $finder->files()->name($locale ? '*.'.$locale.'.*' : '*')->in($translationDir);
64 1
        foreach ($files as $file) {
65
            $this->filesystem->remove($file);
66 1
        }
67
68
        // Build them again
69 1
        if ($this->translator instanceof WarmableInterface) {
70
            $this->translator->warmUp($translationDir);
71
        }
72 1
    }
73
}
74