Passed
Push — master ( ce8562...af7542 )
by Petr
02:11
created

Files::toString()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 0
Metric Value
cc 3
eloc 8
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 14
ccs 7
cts 8
cp 0.875
crap 3.0175
rs 10
1
<?php
2
3
namespace kalanis\kw_menu\MetaSource;
4
5
6
use kalanis\kw_files\Access\CompositeAdapter;
7
use kalanis\kw_files\FilesException;
8
use kalanis\kw_menu\Interfaces\IMetaFileParser;
9
use kalanis\kw_menu\Interfaces\IMetaSource;
10
use kalanis\kw_menu\Interfaces\IMNTranslations;
11
use kalanis\kw_menu\Menu\Menu;
12
use kalanis\kw_menu\MenuException;
13
use kalanis\kw_menu\Traits\TToString;
14
use kalanis\kw_paths\PathsException;
15
16
17
/**
18
 * Class Files
19
 * @package kalanis\kw_menu\MetaSource
20
 * Data source is in passed Files package
21
 */
22
class Files implements IMetaSource
23
{
24
    use TToString;
25
26
    /** @var string[] */
27
    protected $key = [];
28
    /** @var CompositeAdapter */
29
    protected $files = null;
30
    /** @var IMetaFileParser */
31
    protected $parser = null;
32
33
    /**
34
     * @param CompositeAdapter $files
35
     * @param IMetaFileParser $parser
36
     * @param IMNTranslations|null $lang
37
     * @param string[] $metaKey
38
     */
39 8
    public function __construct(CompositeAdapter $files, IMetaFileParser $parser, ?IMNTranslations $lang = null, array $metaKey = [])
40
    {
41 8
        $this->setMnLang($lang);
42 8
        $this->files = $files;
43 8
        $this->parser = $parser;
44 8
        $this->key = $metaKey;
45 8
    }
46
47 4
    public function setSource(array $metaPath): void
48
    {
49 4
        $this->key = $metaPath;
50 4
    }
51
52 5
    public function exists(): bool
53
    {
54
        try {
55 5
            return $this->files->exists($this->key);
56 1
        } catch (FilesException | PathsException $ex) {
57 1
            throw new MenuException($ex->getMessage(), $ex->getCode(), $ex);
58
        }
59
    }
60
61 5
    public function load(): Menu
62
    {
63
        try {
64 5
            return $this->parser->unpack($this->toString($this->files->readFile($this->key)));
65 1
        } catch (FilesException | PathsException $ex) {
66 1
            throw new MenuException($ex->getMessage(), $ex->getCode(), $ex);
67
        }
68
    }
69
70 2
    public function save(Menu $content): bool
71
    {
72
        try {
73 2
            return $this->files->saveFile($this->key, $this->parser->pack($content));
74 1
        } catch (FilesException | PathsException $ex) {
75 1
            throw new MenuException($ex->getMessage(), $ex->getCode(), $ex);
76
        }
77
    }
78
}
79