Completed
Push — master ( 96e036...eed5cf )
by Ben
02:47
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 3
    public function __construct(Filesystem $filesystem)
19
    {
20 3
        $this->filesystem = $filesystem;
21 3
    }
22
23
    /**
24
     * Write all translations to cache
25
     */
26 3
    public function write()
27
    {
28 3
        foreach (config('squanto.locales', []) as $locale) {
29 3
            $this->writeLocale($locale, Line::getValuesByLocale($locale));
30
        }
31
32 3
        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 3
    protected function writeLocale($locale, array $lines = [])
42
    {
43 3
        $translations = ConvertToTree::fromFlattened($lines);
44
45 3
        foreach ($translations as $section => $trans) {
46 3
            $this->filesystem->put(
47 3
                $locale.'/'.$section.'.php',
48 3
                "<?php\n\n return ".var_export($trans, true).";\n"
49
            );
50
        }
51 3
    }
52
53 3
    public function delete($locale = null)
54
    {
55 3
        if ($locale) {
56
            $this->filesystem->deleteDir($locale);
57
        }
58
59 3
        foreach ($this->filesystem->listContents() as $content) {
60 3
            if ($content['type'] == 'dir') {
61 3
                $this->filesystem->deleteDir($content['path']);
62
            } else {
63
                $this->filesystem->delete($content['path']);
64
            }
65
        }
66
67 3
        return $this;
68
    }
69
}
70