Completed
Push — master ( 9ab091...ed74e2 )
by Alexpts
03:14
created

MapsManager::getMap()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
ccs 8
cts 8
cp 1
rs 9.4286
cc 2
eloc 8
nc 2
nop 2
crap 2
1
<?php
2
namespace PTS\DataTransformer;
3
4
use Exception;
5
use Symfony\Component\Yaml\Exception\ParseException;
6
use Symfony\Component\Yaml\Parser as YamlParser;
7
8
class MapsManager
9
{
10
    /** @var YamlParser */
11
    protected $yamlParser;
12
    /** @var array */
13
    protected $cache = [];
14
    /** @var array */
15
    protected $mapsDirs = [];
16
17
    /**
18
     * @param YamlParser $parser
19
     */
20 7
    public function __construct(YamlParser $parser)
21
    {
22 7
        $this->yamlParser = $parser;
23 7
    }
24
25
    /**
26
     * @param string $name
27
     * @param string $dir
28
     * @throws Exception
29
     */
30 6
    public function setMapDir($name, $dir)
31
    {
32 6
        $this->mapsDirs[$name] = $dir;
33 6
    }
34
35
    /**
36
     * @param string $name
37
     * @param string $type
38
     * @return array
39
     *
40
     * @throws ParseException
41
     */
42 5
    public function getMap($name, $type = 'dto')
43
    {
44 5
        $map = $this->tryCache($name, $type);
45 5
        if ($map) {
46 1
            return $map;
47
        }
48
49 5
        $dir = $this->mapsDirs[$name];
50 5
        $map = $this->getByPath($dir . '/' . $type . '.yml');
51
52 5
        $this->setCache($name, $type, $map);
53 5
        return $map;
54
    }
55
56
    /**
57
     * @param string $name
58
     * @param string $type
59
     * @param array $map
60
     */
61 5
    protected function setCache($name, $type, array $map)
62
    {
63 5
        $this->cache[$name][$type] = $map;
64 5
    }
65
66
    /**
67
     * @param string $name
68
     * @param string $type
69
     * @return array|null
70
     */
71 5
    protected function tryCache($name, $type)
72
    {
73 5
        if (isset($this->cache[$name], $this->cache[$name][$type])) {
74 1
            return $this->cache[$name][$type];
75
        }
76
77 5
        return null;
78
    }
79
80
    /**
81
     * @param string $path
82
     * @return array
83
     * @throws ParseException
84
     */
85 5
    protected function getByPath($path)
86
    {
87 5
        return $this->yamlParser->parse(file_get_contents($path));
88
    }
89
}