ReportDataCompiler::compile()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 0
cts 10
cp 0
rs 9.9
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 12
1
<?php
2
namespace Mathielen\ReportWriteEngine\Engine\Compiler;
3
4
use Psr\Log\LoggerInterface;
5
use Psr\Log\NullLogger;
6
7
class ReportDataCompiler
8
{
9
10
    /**
11
     * @var LoggerInterface
12
     */
13
    private $logger;
14
15
    public function __construct(LoggerInterface $logger = null)
16
    {
17
        $this->logger = $logger ? $logger : new NullLogger();
18
    }
19
20
    protected function translate($templateValue, array $data)
21
    {
22
        $translated = $templateValue;
23
24
        if (preg_match('/{{(\w+)}}/', $templateValue, $regs)) {
25
            $key = $regs[1];
26
            if (array_key_exists($key, $data) && !is_Array($data[$key])) {
27
                $translated = preg_replace('/{{(\w+)}}/', $data[$key], $templateValue);
28
            } else {
29
                $this->logger->notice("Could not translate $templateValue", ['data-keys' => array_keys($data)]);
30
                $translated = null;
31
            }
32
        }
33
34
        return $translated;
35
    }
36
37
    public function compile(array $item, array $template)
38
    {
39
        $data = $template;
40
        foreach ($data as &$row) {
41
            foreach ($row as &$col) {
42
                $col['value'] = $this->translate($col['value'], $item);
43
            }
44
        }
45
46
        return $data;
47
    }
48
49
}
50