Completed
Push — master ( fcbc5c...f55285 )
by
unknown
07:48
created

CachedTranslationFile::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Thinktomorrow\Squanto\Services;
4
5
use League\Flysystem\Filesystem;
6
use Thinktomorrow\Squanto\Domain\Line;
7
8
class CachedTranslationFile
9
{
10
    /**
11
     * Local filesystem. Already contains the path to our translation files
12
     * e.g. storage/app/trans
13
     *
14
     * @var Filesystem
15
     */
16
    private $filesystem;
17
18 6
    public function __construct(Filesystem $filesystem)
19
    {
20 6
        $this->filesystem = $filesystem;
21 6
    }
22
23
    /**
24
     * Write all translations to cache
25
     */
26 6
    public function write()
27
    {
28 6
        foreach (config('squanto.locales', []) as $locale) {
29 6
            $this->writeLocale($locale, Line::getValuesByLocale($locale));
30
        }
31
32 6
        return $this;
33
    }
34
35
    /**
36
     * Create new cached translation files based on database entries
37
     *
38
     * @param $locale
39
     * @param array $lines - flat array of key-value pairs e.g. foo.bar => 'translation of foo'
40
     */
41 6
    protected function writeLocale($locale, array $lines = [])
42
    {
43 6
        $translations = ConvertToTree::fromFlattened($lines);
44
45 6
        foreach ($translations as $section => $trans) {
46 6
            $this->filesystem->put(
47 6
                $locale.'/'.$section.'.php',
48 6
                "<?php\n\n return ".var_export($trans, true).";\n"
49
            );
50
        }
51 6
    }
52
53 6
    public function delete($locale = null)
54
    {
55 6
        if ($locale) {
56
            $this->filesystem->deleteDir($locale);
57
        }
58
59 6
        foreach ($this->filesystem->listContents() as $content) {
60 6
            if ($content['type'] == 'dir') {
61 6
                $this->filesystem->deleteDir($content['path']);
62
            } else {
63 6
                $this->filesystem->delete($content['path']);
64
            }
65
        }
66
67 6
        return $this;
68
    }
69
}
70