TranslateMacros   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 11
eloc 24
c 2
b 0
f 0
dl 0
loc 45
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A install() 0 4 1
A containsOnlyOneWord() 0 5 1
B macroTranslate() 0 30 9
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Efabrica\Translatte\Latte;
6
7
use Latte\Compiler;
8
use Latte\Engine;
9
use Latte\MacroNode;
10
use Latte\Macros\MacroSet;
11
use Latte\PhpWriter;
12
13
class TranslateMacros extends MacroSet
14
{
15
    public static function install(Compiler $compiler): void
16
    {
17
        $me = new self($compiler);
18
        $me->addMacro('_', [$me, 'macroTranslate'], [$me, 'macroTranslate']);
19
    }
20
21
    public function macroTranslate(MacroNode $node, PhpWriter $writer): string
22
    {
23
        if ($node->closing) {
24
            if (strpos($node->content, '<?php') === false) {
25
                $value = var_export($node->content, true);
26
                $node->content = '';
27
            } else {
28
                $node->openingCode = '<?php ob_start(function () {}) ?>' . $node->openingCode;
29
                $value = 'ob_get_clean()';
30
            }
31
32
            if (!defined(Engine::class . '::VERSION_ID') || Engine::VERSION_ID < 20804) { // @phpstan-ignore-line
33
                return $writer->write('$_fi = new LR\FilterInfo(%var); echo %modifyContent($this->filters->filterContent("translate", $_fi, %raw))', $node->context[0], $value);
34
            }
35
36
            if (Engine::VERSION_ID >= 20900 && Engine::VERSION_ID < 20902) { // @phpstan-ignore-line
37
                return $writer->write('$__fi = new LR\FilterInfo(%var); echo %modifyContent($this->filters->filterContent("translate", $__fi, %raw))', $node->context[0], $value);
38
            }
39
40
            return $writer->write('$ʟ_fi = new LR\FilterInfo(%var); echo %modifyContent($this->filters->filterContent("translate", $ʟ_fi, %raw))', $node->context[0], $value);
41
        } elseif ($node->args !== '') {
42
            $node->empty = true;
43
            if ($this->containsOnlyOneWord($node)) {
44
                return $writer->write('echo %modify(call_user_func($this->filters->translate, %node.word))');
45
            }
46
47
            return $writer->write('echo %modify(call_user_func($this->filters->translate, %node.word, %node.args))');
48
        }
49
50
        return '';
51
    }
52
53
    private function containsOnlyOneWord(MacroNode $node): bool
54
    {
55
        $result = trim($node->tokenizer->joinUntil(',')) === trim($node->args);
56
        $node->tokenizer->reset();
57
        return $result;
58
    }
59
}
60